LEETCODE-缺失的第一个正数41

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

示例 1:

输入: [1,2,0]
输出: 3
示例 2:

输入: [3,4,-1,1]
输出: 2
示例 3:

输入: [7,8,9,11,12]
输出: 1
说明:

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

解题思路:
第一个未出现的正数应在1-数组长度+1之间。

class Solution {
    public int firstMissingPositive(int[] nums) {
        int[] temp = new int[nums.length+2];
        for(int i = 0;i<nums.length;i++){
            if(nums[i]>0&&nums[i]<=nums.length){
                temp[nums[i]]++;
            }
        }
        int index = 1;
        while(index<temp.length){
            if(temp[index]==0)
                return index;
            index++;
        }
        return 1;      
    }
}

猜你喜欢

转载自blog.csdn.net/u012485480/article/details/80596977
今日推荐