[LeetCode][JavaScript]Single Number II

Single Number II

Given an array of integers, every element appears three times except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

https://leetcode.com/problems/single-number-ii/

 

 


 

 

这种位运算的题超越了我的三观,根本不可能。

https://leetcode.com/discuss/857/constant-space-solution

三个变量分别代表出现了几次。

到最后出现三次的会在threes里,ones里就是结果。

 1 /**
 2  * @param {number[]} nums
 3  * @return {number}
 4  */
 5 var singleNumber = function(nums) {
 6     var ones = 0, twos = 0, threes = 0;
 7     for(var i = 0; i < nums.length; i++){
 8         twos |= ones & nums[i];
 9         ones ^= nums[i];
10         threes = ones & twos;
11         ones &= ~threes;
12         twos &= ~threes;
13     }
14     return ones;
15 };

 

 
posted @ 2015-08-18 22:50  `Liok  阅读(304)  评论(0编辑  收藏  举报