the first missing positive :找第一个丢失的整数
方法1:从1开始寻找正整数result·,找到就把他交换到nums[i]:同时i回退到result+1,时间复杂度大于O(n) AC
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int result = 1;
for (int i = 0; i < nums.size(); ) {
if (nums[i] != result) {
i++;
} else {
// swap
int temp = nums[result - 1];
nums[result - 1] = nums[i];
nums[i] = temp;
i = result++;
}
}
return result;
}
};
方法2:对每一个大于1的数nums[i],都把他放在nums[num[i]-1]上,最后遍历 时间复杂度O(n),AC
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int i, n = nums.size();
for(i=0; i<n; i++)
{
while(nums[i]>=1 && nums[i]<=n && nums[i]!=nums[nums[i]-1])
swap(nums[i], nums[nums[i]-1]);
}
int j=1;
for(j=1; j<=n; j++)
if(nums[j-1]!=j)
break;
return j;
}
};
解法3:
int firstMissingPositive(int A[], int n)
{
int HIT = -199928;
for(int i=0;i<n; i++)
{
int t = A[i];
while(t!=HIT && t>=1 && t<=n)
{
int temp = A[t-1]; A[t-1] = HIT; t = temp;
}
}
for(int i=0; i<n; i++)
{
if(A[i]!=HIT)
return i+1;
}
return n+1;
}
题目:287. Find the Duplicate Number
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int i=0,temp=0,count=0;
while (count!=nums.size()){
if (nums[i]-1!=i){
if (nums[i]==nums[nums[i]-1])
return nums[i];
else{
temp=nums[nums[i]-1];
nums[nums[i]-1]=nums[i];
nums[i]=temp;
count++;
}
}
else i=nums.size()-1;
}
return 0;
}
};
题目:
Longest Consecutive Sequence:
寻找给定数组中的最长连续序列
解法1:先排序,在遍历 时间复杂度O(nlogn)
有趣的是:题目要求时间复杂度O(N),但这种方法不但AC。而且时间上比93%的提交都快,相反下一种解法使用hash,时间复杂度理论上看起来O(N),
但却只比10%的提交快。,所以,只有一种解释,那就是这种看起来时间复杂度是O(N),实际上,当数据长度很大时,平均时间复杂度是大于O(NlogN)的
总结:很大博客上转载的第二种解法并不是O(N)时间复杂度!!!!!!!!!!!!!!!!!!
如下图 12ms的是第一种解法,40毫秒的是第二种解法
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
int seq = 1;
int max = 1;
if (nums.size() == 0)
return 0;
sort(nums.begin(), nums.end());
int i = 0;
while (i + 1 < nums.size())
{
if((nums[i + 1] == nums[i] + 1))
seq++;
else if(nums[i+1]!=nums[i])
{
if (seq>max)
max = seq;
seq = 1;
}
i++;
}
if (seq>max)
return seq;
else
return max;
}
};
解法2:使用hash 用空间换时间
class Solution
{
public:
int longestConsecutive(vector<int> &num)
{
// Note: The Solution object is instantiated only once and is reused by each test case.
map<int,int> hashtable;
for(int i = 0;i < num.size();i++)
{
hashtable[num[i]] = 1;
}
int count = 0;
int max = 0;
for(int i = 0;i < num.size();i++)
{
count = 1;
int curincrease = num[i] + 1;
while( hashtable.find(curincrease) != hashtable.end() )
{
count++;
hashtable.erase(hashtable.find(curincrease));
curincrease++;
}
int curdecrease = num[i] - 1;
while( hashtable.find(curdecrease) != hashtable.end() )
{
count++;
hashtable.erase(hashtable.find(curdecrease));
curdecrease--;
}
if(count > max)
max = count;
}
return max;
}
};