136. Single Number

问题:

给定一组数,其中每个数字都出现2次,

只有一个数字出现了一次。求这个数字。

Example 1:
Input: nums = [2,2,1]
Output: 1

Example 2:
Input: nums = [4,1,2,1,2]
Output: 4

Example 3:
Input: nums = [1]
Output: 1
 
Constraints:
1 <= nums.length <= 3 * 104
-3 * 104 <= nums[i] <= 3 * 104
Each element in the array appears twice except for one element which appears only once.

  

解法:bit 运算

a^a = 0

0^a = a

根据上述异或运算的规则,我们可对数组中的所有数进行累计异或运算。

最后只出现一次的数,则==最后结果。

 

代码参考:

 1 class Solution {
 2 public:
 3     int singleNumber(vector<int>& nums) {
 4         int res = 0;
 5         for(int n:nums) {
 6             res ^= n;
 7         }
 8         return res;
 9     }
10 };

 

posted @ 2021-03-23 13:14  habibah_chang  阅读(25)  评论(0编辑  收藏  举报