[LeetCode] Single Number III
2015-10-28 23:45
155 查看
This problem can also be solved using Hash map and this idea is quite simple on implementation.
But how to do it in linear time and constant space?
First of all, we know that if we do XOR to all the elements, we can get a^b in which a,b are the numbers we want respectively. Now, need to analysis the result of a^b. If any bit is '1' means a and b are different on this bit.
So, we can find this one bit and '&' with all other numbers to get those have the same bit and XOR them. Then we get the number, say a. a^b^a = b. Done.
vector<int> singleNumber(vector<int>& nums) {
int len=nums.size();
vector<int> res;
if(len<2) return res;
int first = 0;
for(int i=0;i<len;i++)
{
first=first^nums[i];
}
int diff = 1;
while((first&diff)!=diff)
{
diff=diff<<1;
}
int result=0;
for(int i=0;i<len;i++)
{
if((nums[i]&diff)==diff)
{
result=result^nums[i];
}
}
res.push_back(result);
res.push_back(first^result);
return res;
}Two things are tricky here: the priority of '&' is somehow lower than != and ==, and diff<<1 won't change diff.
But how to do it in linear time and constant space?
First of all, we know that if we do XOR to all the elements, we can get a^b in which a,b are the numbers we want respectively. Now, need to analysis the result of a^b. If any bit is '1' means a and b are different on this bit.
So, we can find this one bit and '&' with all other numbers to get those have the same bit and XOR them. Then we get the number, say a. a^b^a = b. Done.
vector<int> singleNumber(vector<int>& nums) {
int len=nums.size();
vector<int> res;
if(len<2) return res;
int first = 0;
for(int i=0;i<len;i++)
{
first=first^nums[i];
}
int diff = 1;
while((first&diff)!=diff)
{
diff=diff<<1;
}
int result=0;
for(int i=0;i<len;i++)
{
if((nums[i]&diff)==diff)
{
result=result^nums[i];
}
}
res.push_back(result);
res.push_back(first^result);
return res;
}Two things are tricky here: the priority of '&' is somehow lower than != and ==, and diff<<1 won't change diff.
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解