First Missing Positive

来源:互联网 发布:宋理宗 知乎 编辑:程序博客网 时间:2024/06/13 17:46

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.

Have you been asked this question in an interview? 

这里题目要求是 O(N), 所以也就是说不能够排序。
思路: 把出现的数值放到与下标一致的位置,再判断什么位置最先出现不连续的数值,就是答案了。
有几个需要注意的问题:
1 A[i] 表示 i+1 的值,因为有可能数组表示的值刚好是 1 到 A.length, 所以如果A[i] 表示 i 的话,A[0] 有可能刚好放的值为A.length 
2 while 循环条件有三样,要考虑全面:
while (A[i] != i + 1 && A[i] < A.length && A[i] > 0)
尤其注意A[i] > 0
3 数组中有可能存在重复数据, 如 [1,1], 那么如果没有
if (temp == A[i]) {                    break;                }
则形成infinite loop

代码如下

public class Solution {    public int firstMissingPositive(int[] A) {        if(A == null || A.length == 0) {            return 1;        }        for (int i = 0; i < A.length; i++) {            while (A[i] != i + 1 && A[i] < A.length && A[i] > 0) {                int temp = A[A[i] - 1];                if (temp == A[i]) {                    break;                }                A[A[i] - 1] = A[i];                A[i] = temp;            }        }        for (int i = 0; i < A.length; i++) {            if (A[i] != i + 1) {                return i + 1;            }        }        return A.length + 1;    }}





0 0