题解 | 缺失的第一个正整数

缺失的第一个正整数

https://www.nowcoder.com/practice/50ec6a5b0e4e45348544348278cdcee5

代码看起来简洁,实际上运行效率不高

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param nums int整型一维数组
     * @return int整型
     */
    public int minNumberDisappeared (int[] nums, int method) {
        // 小堆的方式
        PriorityQueue<Integer> queue = new PriorityQueue<>();

        for (int i = 0; i < nums.length; i++) {
            int a = nums[i];
            if (a > 0) {
                queue.offer(a);
            }
        }
        int index = 1;
        while (queue.size() > 0 && queue.poll() == index) {
            index ++;
        }
        return index;
    }

    public int minNumberDisappeared (int[] nums) {
        // HashSet的方式
        int index = 1;
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            int a = nums[i];
            if (a >0 ){set.add(a);}
        }

        while (set.contains(index)) {
            index ++;
        }

        return index;
    }
}

全部评论

相关推荐

02-28 01:18
已编辑
南昌大学 后端工程师
黑皮白袜臭脚体育生:把开源经历放个人项目上边应该更好,就像大部分人都把实习经历放个人项目上边
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务