题目地址:Single Number II - LeetCode
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
这是一道谷歌的面试题
这道题目意思很简单,就是找出没出现3次的数字。
最容易想到的想法是用字典,count。
Python解法如下:
from collections import Counter
class Solution:
def singleNumber(self, nums: List[int]) -> int:
s=Counter(nums)
for i in s:
if s[i]!=3:
return i
然后会想可不可以用位运算,毕竟使用字典还是很费时的。
如何使用三次异或消去出现3次的数字。
官方解法如下:
class Solution:
def singleNumber(self, nums: List[int]) -> int:
seen_once = seen_twice = 0
for num in nums:
# first appearance:
# add num to seen_once
# don't add to seen_twice because of presence in seen_once
# second appearance:
# remove num from seen_once
# add num to seen_twice
# third appearance:
# don't add to seen_once because of presence in seen_twice
# remove num from seen_twice
seen_once = ~seen_twice & (seen_once ^ num)
seen_twice = ~seen_once & (seen_twice ^ num)
return seen_once
异或的解法难度极大,建议去看leetcode的讨论区:
C++解法如下:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int one = 0, two = 0, three = 0;
for (int i = 0; i < nums.size(); ++i) {
two |= one & nums[i];
one ^= nums[i];
three = one & two;
one = one ^ three;
two = two ^ three;
}
return one;
}
};