leetcode: First Missing Positive

来源:互联网 发布:iis中将端口改为81 编辑:程序博客网 时间:2024/04/30 07:14

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.


http://tech-wonderland.net/blog/leetcode-first-missing-positive.html

就是把出现的正整数a都放在a-1的位置,然后从头开始历遍,发现A[i] != i + 1的情况就是所要的结果

class Solution {public:    int firstMissingPositive(int A[], int n) {        if( A == NULL || n == 0)            return 1;//这里返回        for( int i = 0; i < n; ){            if( A[i] != i + 1 && A[i] > 0 && A[i] <= n && A[i] != A[A[i]-1])//这里A[i] > 0不能用A[i]代替                swap( A[i], A[A[i]-1]);//不改变i的值,一直交换,直到不满足上述条件之一            else                ++i;        }        for( int j = 0; j < n; ++j)            if( A[j] != j + 1)                return j + 1;        return n + 1;    }};


0 0
原创粉丝点击