First Missing Positive Given an unsorted integer array, find the first missing positive integer. Fo

来源:互联网 发布:北电网络交换 编辑:程序博客网 时间:2024/05/16 16:59

First Missing Positive


 

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.

Java代码:

public class Solution {   public int firstMissingPositive(int[] A) {    if (A == null || A.length == 0) {        return 1;    }    // Put the corresponding positive value in the index that equals to its value    int len = A.length;    for (int i = 0; i < len;) {        int num = A[i];        if (num > 0 && num < len && num != i && num != A[num]) {            A[i] = A[num];            A[num] = num;        } else {            ++i;        }    }    // Scan the array to find the first value that is not equal to its index, then it is the missing value    // Test small examples first    int missingValue = A[0] == len ? len+1 : len;    for (int i = 1; i < len; ++i) {        if (A[i] != i) {            missingValue = i;            break;        }    }    return missingValue;}}


0 0
原创粉丝点击