码迷,mamicode.com
首页 > 其他好文 > 详细

[容易]落单的数

时间:2016-06-28 21:47:36      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

题目来源:http://www.lintcode.com/zh-cn/problem/single-number/

技术分享

方法:

异或满足交换律,任意两个相同的数可以异或是0。0和任何数异或的结果是该数,那么最后的结果一定是落单的数字。

C++版 VS2012测试通过:

 1 //#include <iostream>
 2 //#include <vector>
 3 //#include <queue>
 4 //#include <algorithm>
 5 //using namespace std;
 6 
 7 class Solution {
 8 public:
 9     /**
10      * @param A: Array of integers.
11      * return: The single number.
12      */
13     int singleNumber(vector<int> &A) {
14         // write your code here
15         int x=0;
16         for (int i = 0; i < A.size(); i++) {
17             x ^= A[i];
18         }
19         return x;
20     }
21 };
22 
23 //测试
24 //int main()
25 //{
26 //    Solution s;
27 //    int a[]={1,2,2,1,3,4,3};
28 //    int i=sizeof(a)/sizeof(int);
29 //    vector<int> v(a,a+i);
30 //    cout<<s.singleNumber(v);
31 //}

Python2.7版 spider测试通过:

 1 class Solution:
 2     """
 3    @param A : an integer array
 4    @return : a integer
 5    """
 6     def singleNumber(self, A):
 7         # write your code here
 8         ans = 0;
 9         for x in A:
10             ans = ans ^ x
11         return ans
12 #测试        
13 #if __name__==‘__main__‘:
14 #    s=Solution()
15 #    n=[1,2,2,1,3,4,3]
16 #    print s.singleNumber(n) 

[容易]落单的数

标签:

原文地址:http://www.cnblogs.com/hslzju/p/5624924.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!