First Missing Positive

First Missing Positive

问题:

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

思路:

  A[A[i]] == A[i] 的经典应用

我的代码:

public class Solution {
    public int firstMissingPositive(int[] nums) {
        if(nums==null || nums.length==0)    return 1;
        int len = nums.length;
        int i = 0;
        while(i < len)
        {
            if(nums[i] <= 0)
            {
                i++;
            }
            else
            {
                int index = nums[i];
                if(index > len)
                {
                    nums[i] = 0;
                    i++;   
                }
                else
                {
                    if(nums[index-1] == index) i++;
                    else
                    {
                        int tmp = nums[index-1];
                        nums[index-1] = nums[i];
                        nums[i] = tmp;
                    }
                }
            }
        }
        for(int k=0; k<len; k++)
        {
            if(nums[k] != k+1)    return k+1;
        }
        return len+1;
    }
    
}
View Code

他人代码:

// SOLUTION 2:
    public int firstMissingPositive(int[] A) {
        // bug 3: when length is 0, return 1;
        if (A == null) {
            return 0;
        }
        for (int i = 0; i < A.length; i++) {
            // 1: A[i] is in the range;
            // 2: A[i] > 0.
            // 3: The target is different;
            while (A[i] <= A.length && A[i] > 0 && A[A[i] - 1] != A[i]) {
                swap(A, i, A[i] - 1);    
            }
        }
        
        for (int i = 0; i < A.length; i++) {
            if (A[i] != i + 1) {
                return i + 1;
            }
        }
        
        return A.length + 1;
    }
View Code

学习之处:

  • 仔细体下面这一段代码,每一个A[i]都有一个使命,什么叫做使命完结了呢,经过跌宕起伏的过程A[i]的值发生了多次变化,但是A[A[i]] == A[i] 成功了,此时此刻使命完结了。
 while (A[i] <= A.length && A[i] > 0 && A[A[i] - 1] != A[i]) {
                swap(A, i, A[i] - 1);    
            }
View Code
  • 改变不好的习惯

posted on 2015-04-27 18:48  zhouzhou0615  阅读(153)  评论(0编辑  收藏  举报

导航