题目
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:1
2Input: [2,2,1]
Output: 1
Example 2:1
2Input: [4,1,2,1,2]
Output: 4
分析
此处为二维的表格构造
在开辟一个数组
判定当i!=j 的时候 在判定是否有相等元素
C代码如下1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52//
// Created by YUGE on 2018/8/25.
//
int singleNumber(int* nums, int numsSize) {
// int num[numsSize];
// 动态开辟数组
int *num=(int*)malloc(numsSize* sizeof(int)) ;
for(int i=0;i<numsSize;i++)
{
// 赋值给另一个数组,是两个数组一致
num[i]=nums[i];
//printf("%d-%d\n",nums[i],num[i]);
}
for(int i=0;i<numsSize;i++)
{
for(int j=0;j<numsSize;j++)
{
// if(i==j)
// {
//// 如果相等则跳过不判断
// continue;
// }
// 两个数相等则这个数出现了两次 直接跳出下面的循环
if(nums[i]==num[j]&&i!=j)
{
break;
}
if(j==(numsSize-1))
{
// 到最后如果没有找到相等的元素则直接可以返回值
//printf("%d\n",nums[i]);
return nums[i];
} //end if
}//end for
} //end for
return 0;
}
int main() {
int nums[] ={2,2,1,1,3};
int numsSize = 0;
numsSize= sizeof(nums)/ sizeof(int);
printf("%d\n",numsSize);
singleNumber(nums,numsSize);
printf("%d\n",singleNumber(nums,numsSize));
return 0;
}