leetcode 41

缺失的第一个正数

Posted by Static on June 27, 2020

题目链接:https://leetcode-cn.com/problems/first-missing-positive/

题目描述


分析

1. 排序+循环


代码实现

public enum Q41 {
    instance;
    public int firstMissingPositive(int[] nums) {
        if(nums==null||nums.length==0)return 1;
        // 排序
        Arrays.sort(nums);
        int l=nums.length;
        // 都是负数 或 都是大于1的正数,直接返回1
        if(nums[l-1]<=0||nums[0]>1){
            return 1;
        }

        int minP=nums[l-1]+1;
        for(int i=l-1;i>0;i--){
            int num=nums[i];
            int last=nums[i-1];
            if(num>=0&&last>=0){
                // 若前后两个数相等或是连续,则跳过
                if(num==last||num==last+1){
                    continue;
                }
                minP=last+1;
            }else if(last<1&&num>1){
                return 1;
            }
        }

        return minP;
    }

    public static void main(String[] args) {
        // assert 3
        System.out.println(Q41.instance.firstMissingPositive(new int[]{1,2,0}));

        // assert 2
        System.out.println(Q41.instance.firstMissingPositive(new int[]{3,4,-1,1}));

        // assert 1
        System.out.println(Q41.instance.firstMissingPositive(new int[]{7,8,9,11,12}));

        // assert 3
        System.out.println(Q41.instance.firstMissingPositive(new int[]{0,1,2,4,-1}));

    }
}

Life is like an ocean.Only the one with resolute mind will reach the other shore. (Germany) Marx

生活就像海洋,只有意志坚强的任才能到达彼岸。– [德] 马克思