剑指 Offer 56 - II. 数组中数字出现的次数 II

在一个数组 nums 中除一个数字只出现一次之外,其他数字都出现了三次。请找出那个只出现一次的数字。

示例 1:

输入:nums = [3,4,3,3]
输出:4

示例 2:

输入:nums = [9,1,7,9,7,9,7]
输出:1

模3
class Solution {
public:
    int singleNumber(vector<int>& nums) {
        vector<int> n(32);
        for (int num : nums) {
            int j = 0;
            while (num != 0) {
                n[j] += num & 1;
                num >>= 1;
                j++;
            }
        }
        int ans = 0;
        for (int i = 0; i < 32; i++) {
            ans += (1 << i)*(n[i] % 3);
        }
        return ans;
    }
};

看到大神写的有限状态机,太强了,勉强理解了意思

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int one=0;
        int two=0;
        for(const auto &e:nums){
            one=one^e&~two;
            two=two^e&~one;
        }
        return one;
    }
};

 

posted on 2022-03-07 14:43  4小旧  阅读(30)  评论(0)    收藏  举报

导航