首页 > 代码库 > leetcode - Single Number

leetcode - Single Number

今天开始刷leetcode上的题,争取校招前刷过一遍,从AC率最高的题目开始刷,不废话了,看题

 

题目:Single Number

Given an 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?

 

个人思路:

1、对数组排序(从小到大或者从大到小)

2、从第一个数开始,与它后面一个数比较,若相同,说明数组中有两个这样的数,若不同,说明数组中只有一个这样的数,也即是我们要获得的数

 

代码(main里面的代码用于测试,提交时只需提交必要代码即可):

 1 #include <algorithm>
 2 #include <iostream>
 3 
 4 using namespace std;
 5 
 6 class Solution
 7 {
 8 public:
 9     int singleNumber(int A[], int n)
10     {
11         int index;
12         sort(&A[0], &A[n]);
13         for (index = 0; index < n; index += 2)
14         {
15             if (A[index] != A[index + 1])
16             {
17                 break;
18             }
19         }
20 
21         return A[index];
22     };
23 };
24 
25 int main()
26 {
27     int A[] = {1, 2, 1, 3, 3, 4, 2, 5, 4};
28     Solution s;
29     int single = s.singleNumber(A, 9);
30     cout << single << endl;
31 
32     system("pause");
33     return 0;
34 }

 

上面的代码先排序,然后遍历数组,由于不是很清楚sort函数的时间复杂度,姑且当作O(nlogn)吧,总的来说,成功AC了,但整个代码的时间复杂度为O(nlogn)

且题目的要求为:Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

上网查找了线性时间复杂度算法,并且实践了一下,在这里与大家分享,原文链接:http://www.cnblogs.com/changchengxiao/p/3413294.html

 

思路:

1、对于异或运算,有a ^ b = b ^ a和0^ a = a

2、那么遍历数组时,将数组所有元素进行异或处理,相同的元素异或结果为0,则最终的异或结果即为只出现一次的元素

 

代码:

 1 #include <algorithm>
 2 #include <iostream>
 3 
 4 using namespace std;
 5 
 6 class Solution
 7 {
 8 public:
 9     int singleNumber(int A[], int n)
10     {
11         //个人思路
12         /*
13         int index;
14         sort(&A[0], &A[n]);
15         for (index = 0; index < n; index += 2)
16         {
17             if (A[index] != A[index + 1])
18             {
19                 break;
20             }
21         }
22 
23         return A[index];
24         */
25 
26         //网上思路
27         int result = 0;
28         for (int i = 0; i < n; ++i)
29         {
30             result ^= A[i];
31         }
32 
33         return result;
34     };
35 };
36 
37 int main()
38 {
39     int A[] = {1, 2, 1, 3, 3, 4, 2, 5, 4};
40     Solution s;
41     int single = s.singleNumber(A, 9);
42     cout << single << endl;
43 
44     system("pause");
45     return 0;
46 }

 

原文链接中还有两个扩展题,可以看看,好了,就到这吧