您的位置:首页 > 其它

leetcode--First Missing Positive

2013-08-25 00:26 417 查看
1.题目描述

[code]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.

[/code]



2.解法分析


解法:遍历数组,将遇到的正数放到对应的位置,也就是正数i应该放在A[i-1]处。

为什么呢?最直接的算法莫过于排序了,但是时间复杂度满足不了要求,然后就是hash了,但是普通的hash无法满足常数量级的额外空间要求,那么这个题目的思路就是用数组本身作为hash的空间,然后就有了这个解法。




class Solution {


public:


int firstMissingPositive(int A[], int n) {


// Start typing your C/C++ solution below


// DO NOT write int main() function


if(n==0)return 1;




int i=0;


while(i<n)


{


    if(A[i]>0&&A[i]<=n)


    {


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


{


    int temp=A[i];


    A[i]=A[A[i]-1];


    A[temp-1]=temp;


    continue;


}


else i++;




}


    


    else 


    {


A[i]=0;i++;


}


}




i=0;


while(i<n)


{


    if(A[i]!=(i+1))return i+1;


    i++;


}




return n+1;


}


};


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: