Single Number I:
Given an array of integers, every element appears twice except for one. Find that single one.
分析:
异或操作,一遍过。
代码:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int len = nums.size();
int n = nums[0];
for(int i =1; i< len; i++)
{
n = n^nums[i];
}
return n;
}
};
Single Number II:
Given an array of integers, every element appears three times except for one. Find that single one.
分析:
出现过三次。确实有办法用纯位操作实现。太难了,没看懂。https://leetcode.com/discuss/6632/challenge-me-thx
简单的做法就是,统计每个bit位出现1的次数,然后对3求余。
代码:
class Solution {
public:
int singleNumber(vector<int>& nums) {
vector<int> result(32, 0);
int len = nums.size();
int n;
int m;
int k;
for(int i =0; i< len; i++)
{
n = nums[i];
k = 1;
for(int j =0; j< 32; j++)
{
m = n >>j;
if(m == 0) break;
if(m & k) result[j] ++;
}
}
k = 0;
for(int i =0; i< 32; i++)
{
k += (result[i] %3 <<i);
}
return k;
}
};
Single Number III:
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
分析:
因为剩下的两个数,一定不同,因此对整个数组做异或操作,最后得到的数里面一定存在某个bit为1,即剩下的两个数,其中一个数,在该bit位的值为1,另外一个为0. 接着,根据这个bit位的值,对原数组进行分组,再利用Single Number的解法,即可分别求出落单的两个数。
代码:
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
vector<int> arr1;
vector<int> arr2;
int len = nums.size();
int n = 0;
for(int i = 0; i< len; i ++)
{
n = n ^ nums[i];
}
int place;
for(int i =0; i< 32; i++)
{
if(n&1)
{
place = 1<<i;
break;
}
n = n>>1;
if(n == 0) break;
}
vector<int> re(2, 0);
for(int i = 0; i< len; i++ )
{
if((nums[i] & place) == 0) re[0] ^= nums[i];
else re[1] ^= nums[i];
}
return re;
}
};