【LeetCode】#41缺失的第一个正数(First Missing Positive)

【LeetCode】#41缺失的第一个正数(First Missing Positive)

题目描述

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

示例

示例 1:

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

示例 2:

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

示例 3:

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

Description

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

Example

Example 1:

Input: [1,2,0]
Output: 3

Example 2:

Input: [3,4,-1,1]
Output: 2

Example 3:

Input: [7,8,9,11,12]
Output: 1

解法

class Solution {
    public int firstMissingPositive(int[] nums) {
        if(nums.length==0)
            return 1;
        Arrays.sort(nums);
        if(nums[0]>1)
            return 1;
        int k = 1;
        for(int i=0; i<nums.length; i++){
            if(nums[i]>k){
                return k;
            }else if(nums[i]==k){
                k++;
            }
        }
        return k;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43858604/article/details/84842057