137. Single Number II - Medium
Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,3,2] Output: 3
Example 2:
Input: [0,1,0,1,0,1,99] Output: 99
reference: https://leetcode.com/problems/single-number-ii/discuss/43302/Accepted-code-with-proper-Explaination.-Does-anyone-have-a-better-idea
对于每一个元素,统计其出现次数,若出现次数达到3,则置为0,最后所有元素的次数都为0,除了只出现一次的元素是1
即0->1->2->0,如果用二进制表示:00->01->10->00。换一种方便的表示方法:00->10->01->00,这样可以用两个参数ones twos来表示,最后返回ones就是只出现一次的数字
ones和twos的变化过程:
0 0 (初始)
0->1 0->0
1->0 0->1
0->0 1->0
遍历整个数组,对每一个元素,先存入ones,再清空ones存入twos,再清空twos
time: O(n), space: O(1)
class Solution { public int singleNumber(int[] nums) { int ones = 0, twos = 0; for(int k : nums) { ones = (ones ^ k) & ~twos; twos = (twos ^ k) & ~ones; } return ones; } }
另一种理解方法:模拟三进制
class Solution { public int singleNumber(int[] nums) { int one = 0, two = 0, three = 0; for(int i = 0; i < nums.length; i++) { two |= one & nums[i]; one ^= nums[i]; three = one & two; one &= ~three; two &= ~three; } return one; } }