Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
Note:
The order of the result is not important. So in the above example, [5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity? 解題思路:有一個數組,其中只有兩個數出現一次,其他數均出現兩次,求出這兩個數。參考signal number的第二種解法:http://blog.csdn.net/sinat_24520925/article/details/45576735 我們將這個數組分成兩個數組,每個數組中都只有一個元素出現一次。也就是先異或所有元素,得到resultExclusive,找到resultExclusive中二進位表示的由右向左的第一位1,則表明數組中有一個一次出現的數該位的值不同,一個為0、另一個為0.下面就好做了,將數組中該位均為0的異或,均為1的異或就可求得只出現一次的那兩個數。 代碼如下:
class Solution {public: vector<int> singleNumber(vector<int>& nums) { vector<int> res; if(nums.size()==0) return res; res.push_back(0); res.push_back(0); int resultExclusive=0; for(int i=0;i<nums.size();i++) resultExclusive^=nums[i]; int indexof1=0; while(((resultExclusive&1)==0)&&(indexof1<8*sizeof(int))) { resultExclusive=resultExclusive>>1; ++indexof1; } for(int i=0;i<nums.size();i++) { if((nums[i]>>indexof1)&1==1) res[0]^=nums[i]; else res[1]^=nums[i]; } return res; }};值得注意的是::
(resultExclusive&1)==0)
(resultExclusive&1)一定要加(),否則因為==的優先順序高於&,會導致while迴圈無法進入。。。。