[Leetcode] First Missing Positive (Java)

来源:互联网 发布:快速建站软件 编辑:程序博客网 时间:2024/04/29 19:13

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://blog.unieagle.net/2012/09/20/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Afirst-missing-positive/

题目的最后一行,要求O(n)实际上暗示了用hash,但是又说要contant space,就没法再开新空间来建hash。
正好这个题目中处理的是1到n的数据,提供了一个将输入的数组同时用作hash表的可能性。
于是算法就是:

  1. 第一遍扫描排除所有非正的数,将它们设为一个无关紧要的正数(n+2),因为n+2不可能是答案
  2. 第二遍扫描,将数组作为hash表来使用,用数的正负来表示一个数是否存在在A[]中。
    当遇到A[i],而A[i]属于区间[1,n],就把A中位于此位置A[i] – 1的数置翻转为负数。
    所以我们取一个A[i]的时候,要取它的abs,因为如果它是负数的话,通过步骤一之后,只可能是我们主动设置成负数的
  3. 第三遍扫描,如果遇到一个A[i]是正数,说明i+1这个数没有出现在A[]中,只需要返回即可。
  4. 上一步没返回,说明1到n都在,那就返回n+1
public class FirstMissingPositive {public int firstMissingPositive(int[] A) {for(int i=0;i<A.length;i++)if(A[i]<=0)A[i]=A.length+2;for(int i=0;i<A.length;i++){if(Math.abs(A[i])<=A.length){int cur = Math.abs(A[i])-1;A[cur] = -Math.abs(A[cur]);}}for(int i=0;i<A.length;i++)if(A[i]>0)return i+1;return A.length+1;}public static void main(String[] args) {int[] A = {3,4,-1,1};System.out.println(new FirstMissingPositive().firstMissingPositive(A));}}


0 0
原创粉丝点击