LeetCode First Missing Positive

来源:互联网 发布:五五开黑历史知乎 编辑:程序博客网 时间:2024/06/05 00:33

题目

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.

 

从头向尾扫描,

如果数i在[1,n],且数i和编号为i-1的数不等,则交换两者。

处理一遍后,所有[1,n]的数在正确的位置上都有出现,

如果相应位置i-1上的数不是i,则数i是缺的,从头向后扫一次即可。

 

代码:

class Solution {public:    int firstMissingPositive(int A[], int n) {        int i=0;while(i<n)//交换元素到合适的位置{if(A[i]>0&&A[i]<=n&&A[i]!=i+1&&A[i]!=A[A[i]-1])swap(A[i],A[A[i]-1]);elsei++;}for(i=0;i<n;i++)//扫描if(A[i]!=i+1)return i+1;return n+1;    }};


 

 

 

 

0 0
原创粉丝点击