码迷,mamicode.com
首页 > 其他好文 > 详细

First Missing Positive

时间:2015-09-14 16:52:06      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:positive   元素   example   

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.


算法思想:

因为要求是O(N)时间,所以不能基于交换的排序方法,又要去常量的空间,

这里可以在原数组上进行操作,

对于数组A[n],可以调整数组,使A[0]=1,A[1]=2,A[2]=3,..即A[i]=i+1;

1.如果A[i]<=0||A[i]>size则表示,数组中没有这些元素应当的位置,直接跳过处理下一个元素,如果A[i]==i+1,说明已经调到了应当位置,也跳过。

2.如果A[i]!=i+1,则说明需要调整,直到调整到1的状态,这里需要注意,如果且A[A[i]-1]]==A[i],即说明要调整的另一个位置已经有合适元素了,则不能调整,这时说明这个整数有两个,跳过处理下一个即可。


 int firstMissingPositive(vector<int>& nums) {

int size = nums.size();

if (size <= 0)

return 1;


for (int i = 0; i<size;){

if (nums[i] <= 0 || nums[i]>size || nums[i] == i + 1){

i++;

continue;

}


if (nums[nums[i] - 1] != nums[i])

swap(nums[i], nums[nums[i] - 1]);

else

i++;

}

for (int i = 0; i<size; ++i){

if (nums[i] != i + 1)

return i+1;

}

return size+1;

}


First Missing Positive

标签:positive   元素   example   

原文地址:http://searchcoding.blog.51cto.com/1335412/1694587

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!