Leetcode 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?
解题思路:
参考答案的,想不出来。
ones
代表第ith 位只出现一次的掩码变量twos
代表第ith 位只出现两次次的掩码变量threes
代表第ith 位只出现三次的掩码变量
Java code :
public int singleNumber(int[] nums) { int ones = 0, twos = 0, threes = 0; for (int i = 0; i < nums.length; i++) { twos |= ones & nums[i]; ones ^= nums[i]; threes = ones & twos; ones &= ~threes; twos &= ~threes; } return ones; }
Reference:
1. http://www.cnblogs.com/springfor/p/3870863.html
2. http://www.programcreek.com/2014/03/leetcode-single-number-ii-java/
3. http://www.acmerblog.com/leetcode-single-number-ii-5394.html