Leetcode——只出現一次的字符

只出現一次的字符I:其餘字符出現兩次

直接將全部數字異或得到結果。

只出現一次的字符II:其餘字符出現三次

用seen_once=~seen_twice&(seen_once^num)

用seen_twice=~seen_once&(seen_twice^num)

來區分出現一次或三次,最後結果爲出現一次。

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int seen_once=0;
        int seen_twice=0;
        for(auto num:nums)
        {
            seen_once=~seen_twice&(seen_once^num);
            seen_twice=~seen_once&(seen_twice^num);
        }
        return seen_once;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章