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