[LintCode] First Missing Positive

Problem

Given an unsorted integer array, find the first missing positive integer.

Example

Given [1,2,0] return 3,
and [3,4,-1,1] return 2.

Note

找第一个缺失的正整数,只要先按顺序排列好[1, 2, 3, 4, ...],也就是A[i] = i+1,找到第一个和A[i]不对应的数i+1就可以了。注意数组的index从0开始,而正整数从1开始,所以重写排列的时候要注意换成index-1,而index就是从A[0]开始的数组A[]中的元素。
我们看一个例子:

[2, 4, -1, 1] --> first for loop --> if (A[i] E (0, A.length) && A[i] != A[A[i]-1]) --> swap(A[i], A[A[i]-1]) --> [4, 2, -1, 1] --> [1, 2, -1, 4] --> second for loop --> A[2] != 3 --> return 2+1 = 3.

之前犯了一个错误,因为第二行A[i]的值已经变了,第三行再代入A[A[i]-1]就会出错:

int temp = A[i];
A[i] = A[A[i]-1];
A[A[i]-1] = temp;

Solution

public class Solution {
    public int firstMissingPositive(int[] A) {
        int len = A.length;
        for (int i = 0; i < len; i++) {
            if (A[i] > 0 && A[i] < len && A[i] != A[A[i]-1]) {
                int temp = A[A[i]-1];
                A[A[i]-1] = A[i];
                A[i] = temp;
                i--; //after the exchange, we need to speculate 
                     //and sort that digit again.
            }
        }
        for (int i = 0; i < len; i++) {
            if (A[i] != i + 1) return i+1; //as array index starts from 0 
                                           //and positive starts from 1.
        }
        return len + 1; //if the array has 1(A[0]) to len(A[len-1])
                        //and missed no one, return the len+1.
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值