只出現一次的字符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;
}
};