Single Number
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
class Solution {
public:
int singleNumber(vector<int>& nums) {
if(nums.empty()) return 0;
int len=nums.size(),ires=nums[0];
for(int i=1;i<len;++i)
{
ires^=nums[i];
}
return ires;
// unordered_map<int,int> mNums;
// for(const int &im:nums)
// {
// ++mNums[im];
// }
// for(const pair<int,int> &pm:mNums)
// {
// if(pm.second==1)
// {
// return pm.first;
// }
// }
// return -1;
}
};
异或比hash来的快。只是我想不出来。
Reference:
http://www.cnblogs.com/changchengxiao/p/3413294.html
异或性质:a^a=0,a^0=a,a^b=b^a。
最终出现两次的都变为0,出现一次的被留下。
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?
class Solution {
public:
int singleNumber(vector<int>& nums) {
int one{},two{},three{},len=nums.size();
for(int j=0;j<len;++j)
{
two|=one&nums[j];//出现两次
one^=nums[j];//出现一次
three=one&two;//出现三次
//将出现三次的置位
one&=~three;
two&=~three;
}
return one;
// int bit[32]{},len=nums.size(),res{};
// for(int i=0;i<32;++i)
// {
// for(int j=0;j<len;++j)
// {
// if((nums[j]>>i)&1)//最低位1 or 0
// ++bit[i];
// }
// /*100(4),100(4),100(4),110(5)
// *4,1,0%3--1,1,0--110
// */
// res|=((bit[i]%3)<<i);
// }
// return res;
}
};
Reference:
http://blog.csdn.net/jiadebin890724/article/details/23306837
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].
Note:
The order of the result is not important. So in the above example, [5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int res{};
//求出XOR
for(const int &im:nums)
{
res^=im;
}
int pos=1;//寻找XOR的第一个置位pos
for(int i=0;i<32;++i)
{
pos<<=i;
if(res&pos)
{
break;
}
}
int res1{};
res=0;
/*根据pos分类XOR
*1, 2, 1, 3, 2, 5
*pos=2
*res:2,2,3
*res1:1,1,,5
*/
for(const int &im:nums)
{
if(pos&im)
{
res^=im;
}
else
{
res1^=im;
}
}
return vector<int>{res,res1};
}
};
不得不说上面三个题目没有一个自己想出来了,都是看的别人解法。看来还要好好学。