LeetCode 41 First Missing Positive(找到数组中第一个丢失的正数)

 
给出一个未排序的数组,求出第一个丢失的正数。
给出组合为int []nums = {0,1,3,-1,2,5};
下面为按照参考代码1执行交换运算的输出结果
 
0 1 3 -1 2 5
1 0 3 -1 2 5
1 0 3 -1 2 5
1 0 3 -1 2 5
1 0 3 -1 2 5
1 2 3 -1 0 5
1 2 3 -1 0 5
1 2 3 -1 5 0
1 2 3 -1 5 0
4
 
参考代码1: 
public class Solution41 {
    public int firstMissingPositive(int[] A) {
    // added line9 condition to avoid infinite loop
    // added line13, the i--, to check the swapped item. Or we failed to check all the numbers.
    // ref http://stackoverflow.com/questions/1586858/find-the-smallest-integer-not-in-a-list
            if (A.length == 0) return 1;//长度等于0 直接返回1
            for (int i = 0; i < A.length; i++) {//遍历
                        //是整数,小于数组长度,不等于当前下标
                if (A[i] <= A.length && A[i] > 0 && A[i] != i+1) {
                    if (A[A[i]-1] != A[i]) { //line 9 进行交换操作
                        int tmp = A[A[i]-1];
                        A[A[i]-1] = A[i];
                        A[i] = tmp;
                        i--; //line 13
                    }
                }            
            }
            for (int i = 0; i < A.length; i++) {
                if (A[i] != i+1) return i+1;
            }
            return A.length+1;
    }
}

参考代码2:

package leetcode_50;


/***
 * 
 * @author pengfei_zheng
 * 找到第一个丢失的正数
 */
public class Solution41 {
    public static int firstMissingPositive(int[] nums) {
        int i = 0;
        while(i < nums.length){
            if(nums[i] == i+1 || nums[i] <= 0 || nums[i] > nums.length) i++;
            else if(nums[nums[i]-1] != nums[i]) swap(nums, i, nums[i]-1);
            else i++;
        }
        i = 0;
        while(i < nums.length && nums[i] == i+1) i++;
        return i+1;
    }

    private static void swap(int[] A, int i, int j){
        int temp = A[i];
        A[i] = A[j];
        A[j] = temp;
    }
    public static void main(String[]args){
        int []nums = {1,1};
        System.out.println(firstMissingPositive(nums));
    }
}
 
 
原文地址:https://www.cnblogs.com/zpfbuaa/p/6537774.html