Problem:
Given an array of integers, every element appears twice except for one. Find the single one.
Note:
Your algorithm should has a linear runtime complexity. Could you implement it without using extra memory?
Hide TagsHash Table Bit manipulationTest instructions: A group of numbers, only one number appears once, the other number appears two times, find out the number
Thinking:
(1) The bitwise operation, the XOR operator
0^a=a;
a^a=0;
A^b=b^a;
(2) The solution to this problem comes out: N number of different or result is to be asked
Code
Class Solution {public: int singlenumber (vector<int>& nums) { int n=nums.size (); int ret=nums[0]; for (int i=1;i<n;i++) ret^=nums[i]; return ret; }};
Extension, refer to http://www.cnblogs.com/changchengxiao/p/3413294.html
1. There are two elements in an array that occur only once, and all the other elements appear two times, to find the two elements that appear only once
[Ideas for solving problems]
Sets all the elements of an array to be different or to get a result that is not 0, according to one of the non-0 in this result, divides the array into two groups
If the elements in the two groups are different or if the XOR value of two arrays is not 0, the final result is obtained
2. One element in an array appears only 1 times, and all other elements appear k times, asking for the element that only appears 1 times
[Ideas for solving problems]
When k is even, the same as LSS
When k is odd, add a mod k to each of the elements in the array, get the result 1 elements of the throne, Time complexity O (nlen), Space complexity O (1)
Leetcode | | 136, single number