Leetcode Single Number II (面试题推荐)

时间:2023-03-09 05:15:36
Leetcode Single Number II (面试题推荐)

还记得《剑指offer》和《编程之美》等书上多次出现的找一个数组中仅仅出现一次的数那个题吗?

leetcode也有这道题 链接here  相信大家都知道用异或在O(n)的时间复杂度内求出的方法,这里不再赘述。

以下就是上题的升级版

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?

给你一个整数数组。每一个元素出现了三次。但仅仅有一个元素出现了一次,让你找出这个数。要求线性的时间复杂度,不使用额外空间。

这样就不能使用异或的方法了。把全部元素以后得到的就是全部元素的异或值了,对我们没有不论什么帮助。

这个问题依然使用位运算来解决,只是更加复杂。

我们用三个变量one two three,分别存储二进制未分别出现一次 两次 三次的位。

class Solution {
public:
int singleNumber(int A[], int n) {
int one = 0, two = 0, three = 0;
for(int i = 0; i < n; i++)
{
three = two & A[i]; //出现三次的位肯定是由出现两次的得到的
two = two | ones & A[i]; //出现两次的肯定是出现一次的得到的,只是还有原有的所以要或
one = one | A[i]; //计算出现一次的位
two = two & ~three; //去掉二进制中出现三次的位
ones = one & ~three; //去掉二进制中出现三次的位</span>
}
return one; //终于twos three都为0。one就是我们要的答案
}
};