LeetCode Single Number II

链接: https://oj.leetcode.com/problems/single-number-ii/

虽然知道这个题肯定跟位运算,异或有关...但实在没想出来怎么解决

class Solution {
public:
    int singleNumber(int A[], int n) {
        int l=0,r=1;
        sort(A,A+n);
        if(n==1)
            return A[0];
        while(A[l]==A[r])
        {
            l+=3;
            r+=3;
            if(r>=n)
                break;
        }
        return A[l];
    }
};

后来google了一下

:如果别的数字都出现两次,那么解决方法是分别对n个数字异或(见 Single Number)..而异或的实质就是按位模2加,所以,这题的思路就是模拟按位模3加:把出现3次1的位置0,而出现1次1的置1;

该代码来自网络:

class Solution {
public:
    int singleNumber(int A[], int n) {
        int one = 0;
        int two = 0;
        int three = 0;
        for(int i = 0 ; i < n ; i++){
            two |= A[i] & one;
            one = A[i] ^ one;
            three = ~(one&two);
            one &= three;
            two &= three;
        }
        return one;
    }
};



你可能感兴趣的:(LeetCode)