Hash:找出第一个缺失的最小正整数

题目:https://www.nowcoder.com/practice/50ec6a5b0e4e45348544348278cdcee5?tpId=295&tqId=2188893&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Foj
题目给出一个没有排序过的数组,然后在数组中找出一个在这里数组中没有出现过的数字中的最小正整数。可以用哈希表存放每一个数组元素,然后再用temp = 0保证这是最小的正整数,然后不对对比哈希表中,temp不断自加,最后到存在了还没出现过的key即暂停循环,直接返回temp
图片说明

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param nums int整型一维数组 
     * @return int整型
     */
    public int minNumberDisappeared (int[] nums) {
        // write code here
        int n = nums.length;
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < n; i++) {
            map.put(nums[i],1);
        }
        int temp = 1;
        while(map.containsKey(temp))
            temp++;
        return temp;
    }
}
全部评论
这道题是什么级别的?简单?
点赞 回复 分享
发布于 2022-08-03 14:47

相关推荐

评论
1
1
分享

创作者周榜

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