【两次过】Lintcode 189. 丢失的第一个正整数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/86559751

给出一个无序的整数数组,找出其中没有出现的最小正整数。

样例

如果给出 [1,2,0], return 3
如果给出 [3,4,-1,1], return 2

挑战

只允许时间复杂度O(n)的算法,并且只能使用常数级别的空间。


解题思路:

使用一个大数组存放对应下标的数字是否出现过,出现设为1,没出现为0

然后从1处遍历这个大数组,一旦遇到0表示找到没有出现的最小正整数

public class Solution {
    /**
     * @param A: An array of integers
     * @return: An integer
     */
    public int firstMissingPositive(int[] A) {
        // write your code here
        int[] nums = new int[10000];
        
        for(int i=0; i<A.length; i++)
            if(A[i] > 0)
                nums[A[i]] = 1;
            
        for(int i=1; i<nums.length; i++)
            if(nums[i] == 0)
                return i;

        return 1;
    }
}

猜你喜欢

转载自blog.csdn.net/majichen95/article/details/86559751