题解 | #没有出现的编号#

没有出现的编号

https://www.nowcoder.com/practice/875d705df65c401a905f574070e09320

知识点:数组

题目要求找到两个值,一个是没出现的最小正整数,一个是最大的负数,我们遍历一次数组,就可以找到最大的负数,而对于没出现的最小正整数,我们可以使用Set集合来存储出现了的正整数,遍历完整个数组后,从1开始递增,判断是否在Set集合中,如不在,则说明我们找到了没出现的最小正整数。

Java题解如下

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param nums int整型一维数组 
     * @return int整型一维数组
     */
    public int[] findMissingAndMaxNegative (int[] nums) {
        // write code here
        int negative = 0;
        Set<Integer> set = new HashSet<>();
        for(int num: nums) {
            if(num < 0) {
                if(negative == 0) {
                    negative = num;
                }else {
                    negative = Math.max(negative, num);
                }
            }else if(num > 0) {
                set.add(num);
            }
        }
        int min = 1;
        while(set.contains(min)) {
            min++;
        }
        return new int[]{min, negative};
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
03-29 08:32
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务