[LeetCode]Single Number II

Single Number II

Given an array of integers, every element appears three times except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

使用hash table可以,但是使用了额外的空间。

要想不使用额外空间,可以运用位运算。

所有和出现次数的题目都可以用位运算,Majority Element也可以的。

 1 class Solution {
 2 public:
 3     int singleNumber(vector<int>& nums) {
 4         int result=0;
 5         vector<int> bit(32,0);
 6         for(int i=0;i<nums.size();i++)
 7         {
 8             int temp = nums[i];
 9             for(int j =0;j<32;j++)
10             {
11                 bit[j]+=((temp>>j) & 0x01);
12                 bit[j]%=3;
13             }
14         }
15         for(int j=0;j<32;j++)
16         {
17             result+=bit[j]<<j;
18         }
19         return result;
20     }
21 };
原文地址:https://www.cnblogs.com/Sean-le/p/4787018.html