[LeetCode][JavaScript]Single Number III
Single Number III
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?
https://leetcode.com/problems/single-number-iii/
又是奇妙的位运算。
https://leetcode.com/discuss/52351/accepted-java-space-easy-solution-with-detail-explanations
第一轮遍历利用异或去掉出现两次的数,留下两个出现一次数的异或。
由于两个数不同,异或的结果中肯定有一位是1。
再遍历输入数组的时候,把输入的数与这一位做与运算,根据结果是否为零,可以把数组分为两份。
结果的两个数会被分开,异或去掉出现两次的数,最后得出答案。
1 /** 2 * @param {number[]} nums 3 * @return {number[]} 4 */ 5 var singleNumber = function(nums) { 6 var two = 0, i; 7 for(i = 0; i < nums.length; i++){ 8 two ^= nums[i]; 9 } 10 var pos = 1; 11 two = two.toString(2); 12 for(i = two.length - 1; i >= 0; i--){ 13 if (two[i] === '1'){ 14 break; 15 } 16 pos *= 2; 17 } 18 var half1 = 0, half2 = 0; 19 for(i = 0; i < nums.length; i++){ 20 if(nums[i] & pos){ 21 half1 ^= nums[i]; 22 }else{ 23 half2 ^= nums[i]; 24 } 25 } 26 return [half1, half2]; 27 };