Given 2*n + 1 numbers, every numbers occurs twice except one, find it.

 
Example

Given [1,2,2,1,3,4,3], return 4

Challenge

One-pass, constant extra space.

 

题意

给出2*n + 1 个的数字,除其中一个数字之外其他每个数字均出现两次,找到这个数字。

 

解法一:

 1 class Solution {
 2 public:
 3     /*
 4      * @param A: An integer array
 5      * @return: An integer
 6      */
 7     int singleNumber(vector<int> &A) {
 8         int num = A[0];
 9         for (int i = 1; i < A.size(); ++i) {
10             num ^= A[i];
11         }
12         
13         return num;
14     }
15 };

利用异或的性质,相同为0

 

相关文章:

猜你喜欢
  • 2021-11-28
  • 2022-12-23
  • 2021-12-13
  • 2021-12-09
  • 2022-12-23
  • 2021-07-21
  • 2021-08-11
相关资源
相似解决方案