1、不重复的数字(LeetCode-136)
Given a non-empty 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?
Example 1:
Input: [2,2,1] Output: 1
Example 2:
Input: [4,1,2,1,2] Output: 4
思路:利用相同数字的异或结果为0这个技巧
class Solution {
public:
int singleNumber(vector<int>& nums) {
int val = 0;
for(int i=0; i<nums.size(); i++)
{
val ^= nums[i];
}
return val;
}
};2、不重复的数字-II
Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,3,2] Output: 3
Example 2:
Input: [0,1,0,1,0,1,99] Output: 99
class Solution {
public:
int singleNumber(vector<int>& nums) {
int ret = 0;
for(int i=0; i<sizeof(int)*8; i++)
{
int sum = 0;
for(int j=0; j<nums.size(); j++)
{
sum += ((nums[j]>>i) & 0x1);
}
ret |= ((sum%3) << i);
}
return ret;
}
};3、不重复的数字-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?
思路:所有数据抑或之后,如果某一bit为1,说明在该bit上,不重复的数字一个为0、一个为1;找到一个为1的bit,根据该bit是否为1,将数据分成两部分,那么不重复的数字分别在两个部分里面;对于任意一个部分,除了不重复值之外,其它均是成对出现。
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
vector<int> ret;
int value = 0;
int a = 0;
int b = 0;
//先求异或
for(unsigned int i=0; i<nums.size(); i++)
{
value ^= nums[i];
}
//找一个为1的bit,这个bit为1,表示只出现一次的两个数在此比特不同
value = value&(value-1)^value;
//从这个为1的bit将数据分成两部分
for(unsigned int i=0; i<nums.size(); i++)
{
if( value & nums[i])
{
a ^= nums[i];
}
else
{
b ^= nums[i];
}
}
ret.push_back(a);
ret.push_back(b);
return ret;
}
};

这篇博客探讨了LeetCode中的三个问题,每个问题都涉及到寻找数组中出现一次的唯一数字。第一题要求找到一个出现一次的数字,第二题要求找到出现一次的两个数字,第三题则要求找到出现两次的两个元素。博主提供了线性时间复杂度且不使用额外内存的解决方案,主要利用了异或操作的特性来定位不重复的数字。

855

被折叠的 条评论
为什么被折叠?



