您的位置:首页 > 其它

LeetCode OJ:First Missing Positive (第一个丢失的正数)

2015-10-10 22:33 429 查看
在leetCode上做的第一个难度是hard的题,题目如下:

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.

关键是要实现0(N)的时间复杂度以及常数级别的空间复杂度,先贴上我写的函数,完全不能达到上面的要求,只能实现NlgN的时间复杂度:

class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
sort(nums.begin(), nums.end());
int sz = nums.size();
if(sz == 0) return 1;
int index;
for (index = 0; index < sz; index++){
if (nums[index] <= 0)
continue;
else
break;
}
if (nums[index] != 1 || index == sz) return 1;  //当没有正数的情况或正数的第一个数不是1的情况
while (index < sz){
if (nums[index + 1] != nums[index] && nums[index + 1] != nums[index] + 1) //两个判断主要是为了防止vector中重复的数字出现。
return nums[index] + 1;
index++;
}
return nums[index] + 1;
}
};


由于达不到时间以及空间复杂度的要求,实在想不出来,我去看了下别人写的,现在由于vector可能会出现重复的数,我暂时不知带怎样去解决,只有先这样,回头有时间再回来填坑。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: