LeetCode:Single Number

Single Number

Total Accepted: 98435  Total Submissions: 210216  Difficulty: Medium

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?

Subscribe to see which companies asked this question

Hide Tags
  Hash Table Bit Manipulation
Hide Similar Problems


解题思路:
1.题目要求找出数组中只出现一次的数;
2.xor异或规则:
a^a = 0;
a^0 = a;
所以,对数组N[N1,N1,N2,...,Nk]的异或(假设Ni是唯一的数):

N1^N1^N2^N2^......^Ni^......^Nk^Nk
=(N1^N1)^(N2^N2)^......^Ni^......^(Nk^Nk)
=0^0^......^Ni^......^0
=Ni

因此,代码如下:
class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int ans = nums[0];
        for(int i=1;i<nums.size();i++) ans^=nums[i];
        return ans;
    }
};


你可能感兴趣的:(异或,number,single,位操作,LeetCodeOJ)