6.6 First Missing Positive

来源:互联网 发布:苹果launchpad软件 编辑:程序博客网 时间:2024/05/20 03:43

Link: https://oj.leetcode.com/problems/first-missing-positive/

My first thought is to create a hashmap of <Integer, Boolean>. Then go through the array A, e.g. for array element 1, we update the value to true on key 1. 

Then we traverse the hashmap to get the first false after key 0. 

Second thought: we cannot do sorting, since no sorting algo is O(n). //This is wrong. Only comparison sorting algorithms are bound by O(nlogn).

Solution: The idea is similar to Counting Sort. Since we can only use constant space, we can only use the array itself. In the first loop, we save positive numbers into the array in ascending order, A[0] = 1, A[1] = 2, A[2] = 3, ... by swapping array elements. We skip negative numbers, 0, and positive numbers whose values are larger than the array length. For the second loop, we check the first element which does not have A[i] = i+1.  (Ref: http://blog.csdn.net/linhuanmars/article/details/20884585)

Time: O(2n) = O(n), Space: O(1)

Note: We cannot use swap(a, b) method to swap A[A[i]-1] and A[i]. Why?


(Figure: http://www.cnblogs.com/AnnieKim/archive/2013/04/21/3034631.html)

public class Solution {    public int firstMissingPositive(int[] A) {        //code after reading the answer        int n = A.length;        int i = 0;        while(i < n){            if(A[i] > 0 && A[i] <= n && A[i] != (i+1) && A[A[i] - 1] != A[i]){                //swap(A[A[i]-1], A[i]);                 int tmp = A[A[i]-1];                 A[A[i]-1] = A[i];                 A[i] = tmp;            }            else i++;        }        for(i = 0; i < n; i++){            if(A[i] != i+1) return i+1;        }        return n+1;    }        //private void swap(int a, int b){        //int tmp = a;        //a = b;        //b = tmp;    //}}




0 0
原创粉丝点击