First Missing Positive

来源:互联网 发布:网络用语gb是什么意思 编辑:程序博客网 时间:2024/06/11 19:39

First Missing PositiveMar 8 '12

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.


可以知道结果不会是<1或者>n+1的,那么把位于这个区间内的A[i]交换到index = A[i]-1的位置上,再扫描一遍就可以得到结果。

class Solution {public:    int firstMissingPositive(int A[], int n) {        // Start typing your C/C++ solution below        // DO NOT write int main() function                for(int i = 0;i < n;)        {            if(A[i] == i+1 || A[i] < 1|| A[i] >n || A[i] == A[A[i]-1]) i++;            else{                swap(A[i],A[A[i]-1]);            }        }                int i = 0;        for(;i<n;i++)        {            if(A[i] != i+1) break;        }        return i+1;    }};

24 milli secs





原创粉丝点击