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.javascript
Example:java
Input: [1,2,1,3,2,5] Output: [3,5]
Note:數組
[5, 3]
is also correct.給定一個數組,其中只有兩個數只出現了一次,其餘全部數都出現了兩次。要求找出這兩個數。app
最簡單的作法就是使用Set進行操做,將已出現過的從Set中除去,將未出現過的加入到Set中。最後留下的就是要找的兩個數。spa
與 0136. Single Number 使用的方法相同,用異或找出這兩個數a和b,具體方法以下:code
class Solution { public int[] singleNumber(int[] nums) { Set<Integer> set = new HashSet<>(); for (int num : nums) { if (set.contains(num)) { set.remove(num); } else { set.add(num); } } int[] ans = new int[set.size()]; int index = 0; for (int num : set) { ans[index++] = num; } return ans; } }
class Solution { public int[] singleNumber(int[] nums) { int[] ans = new int[2]; int xor = 0; for (int num : nums) { xor ^= num; } int pos = 1; while ((xor & pos) == 0) { pos <<= 1; } for (int num : nums) { if ((num & pos) == 0) { ans[0] ^= num; } else { ans[1] ^= num; } } return ans; } }
/** * @param {number[]} nums * @return {number[]} */ var singleNumber = function (nums) { let xor = 0 for (let num of nums) { xor ^= num } let pos = 1 while (!(pos & xor)) { pos <<= 1 } let a = 0 let b = 0 for (let num of nums) { if (num & pos) { a ^= num } else { b ^= num } } return [a, b] }
參考ip