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; } }