260. Single Number III - Medium
阿新 • • 發佈:2018-12-09
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.
Example:
Input:[1,2,1,3,2,5]
Output:[3,5]
Note:
- The order of the result is not important. So in the above example,
[5, 3]
- Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
和136不同的是,這裡有2個只出現一次的數字。還是先把所有數字xor一遍,出來的結果是這兩個數的xor,即 tmp = a ^ b,現在需要分離這兩個數。可以任選其中的一個為1的位,比如tmp & -tmp,是最右的1,然後把tmp和所有數字相與(&),通過這一步可以把答案的兩個數分到兩個組,然後再對兩個小組分別異或,就可以得到這兩個數
time: O(N), space: O(1)
class Solution { public int[] singleNumber(int[] nums) { int[] res = new int[2]; int tmp = 0; for(int k : nums) { tmp ^= k; } tmp &= -tmp; for(int k : nums) { if((k & tmp) == 0) res[0] ^= k;else res[1] ^= k; } return res; } }
reference: http://www.cnblogs.com/grandyang/p/4741122.html