当前位置: 代码迷 >> 综合 >> Single Number II leetcode
  详细解决方案

Single Number II leetcode

热度:70   发布时间:2024-01-14 06:32:02.0

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?

给一个数组,里面只有一个数字一次,其它数字都出现3次,找出这个出现一次的数字,要求时间复杂度为O(n),空间复杂度为O(1)。

以后记住,出现几次的问题要考虑到用位运算解答。下面给出两种方法解答:

第一种: int 数据共有32位,可以用32变量存储 这 N 个元素中各个二进制位上  1  出现的次数,最后 在进行 模三 操作,如果为1,那说明这一位是要找元素二进制表示中为 1 的那一位。代码如下:

class Solution {
public:int singleNumber(int A[], int n) {int bits[32] = {0};int res = 0;for(int i=0;i<32;i++) {for(int j=0;j<n;j++) {bits[i] += (A[j] >> i) & 1;}res |= ((bits[i]%3) << i);}return res;}
};

O(32*N),这是一个通用的解法,如果把出现3次改为 k 次,那么只需模k就行了。

解法二:
这是一个更快一些的解法,利用三个变量分别保存各个二进制位上 1 出现一次、两次、三次的分布情况,最后只需返回变量一就行了。
一个比较好的方法是从位运算来考虑。每一位是0或1,由于除了一个数其他数都出现三次,我们可以检测出每一位出现三次的位运算结果再加上最后一位即可。

class Solution {
public:int singleNumber(int A[], int n) {int ones = 0, twos = 0, threes = 0;for(int i = 0; i < n; i++){threes = twos & A[i]; //已经出现两次并且再次出现twos = twos | ones & A[i]; //曾经出现两次的或者曾经出现一次但是再次出现的ones = ones | A[i]; //出现一次的twos = twos & ~threes; //当某一位出现三次后,我们就从出现两次中消除该位ones = ones & ~threes; //当某一位出现三次后,我们就从出现一次中消除该位}return ones; //twos, threes最终都为0.ones是只出现一次的数}
};


  相关解决方案