LeetCode----Single NumberII

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?


分析:

数组中其他元素均出现3次,只有一个元素只出现过一次,找出那个single元素。

此题有两种解法。


解法一:

对于两个元素,我们使用异或操作即让它清零,即不影响后面的操作,有A^B^A = B. 而当元素为三个时,如何让A*B*A*A = B呢(注意*表示为一种运算,能够满足该表达式)?

我们使用跟3取余的方式来处理。

这种方式适合这类题目的解法,比如所有元素出现m次,一个元素出现1次,可以与m取余。


代码:

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int res = 0;
        int k = 0;
        while(k < 32){
           int temp = 0;
           for(int i=0; i<nums.size(); i++){
               temp += ((nums[i] >> k) & 1 );
           }  
           if(temp%3 != 0){
               res = res | (1<<k);
           }   
           k++;
        }
        return res;
    }
};


解法二:

利用二进制模拟三进制,比如用a,b描述1的状态,

当A出现了一次,a,b的状态为:

0,0 -> 1, 0

出现了两次,a,b的状态为:

1, 0 -> 0, 1

出现了三次,a,b的状态为:

0, 1 -> 1, 1

而当a,b的状态为1,1时,即可以知道当前A已经出现过三次了,将它们清零:

1,1 -> 0,0


代码:

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int ones = 0, twos = 0, threes = 0;
        for(int i = 0 ; i < nums.size() ; i++){
            twos |= (ones & nums[i]);
            ones ^= nums[i];
            threes = ~(ones & twos);
            ones &= threes;
            twos &= threes;
        }
        return ones;
    }
};

你可能感兴趣的:(位运算,LeetCode,python,面试题)