您的位置:首页 > 其它

First Missing Positive

2016-07-21 15:12 183 查看
Given an unsorted integer array, find the first missing positive integer.

For example,
Given
[1,2,0]
return
3
,
and
[3,4,-1,1]
return
2
.

Your algorithm should run in O(n) time and uses constant space.

Analyse:

1. Newest method: 0ms

class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
if(nums.empty()) return 1;

nums.push_back(-1);
for(int i = 0; i < nums.size(); i++){
while(nums[i] > 0 && nums[i] < nums.size() && i < nums.size()) {
if(nums[i] != i && nums[i] != nums[nums[i]])
swap(nums[nums[i]], nums[i]);
else i++;
}
}
for(int i = 1; i < nums.size(); i++){
if(nums[i] != i) return i;
}
return nums.size();
}
};


2. Old method

class Solution {
public:
// Create a new vector of size nums.size()
// Ignore the negative values and values larger than nums.size()
// Put corresponding numbers in the array
// Scan the array for the second time
int firstMissingPositive(vector<int>& nums) {
if(nums.empty()) return 1;

int n = nums.size();
vector<int> temp(n + 1, 0); // Index start from 0
for(int i = 0; i < nums.size(); i++){
if(nums[i] < 0 || nums[i] > n)
continue;
temp[nums[i]] = nums[i];
}
for(int i = 1; i <= n + 1; i++){
if(temp[i] == 0) return i;
}
return n + 1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: