LeetCode448
= =…现在是看到这种题就用hashmap…以前不会用的时候速度快的飞起,一用速度就拉跨…
题目
给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
示例:
输入:
[4,3,2,7,8,2,3,1]
输出:
[5,6]
通过次数51,717提交次数86,342
代码
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
Map<Integer,Integer> hmap = new HashMap<>();
//boolean[] map = new boolean[n];
for (int i:nums)
{
hmap.put(i,hmap.getOrDefault(i,0)+1);
//记录有哪些数 这里其实可以用boolean[] map代替,速度会快蛮多
}
List<Integer> ans = new ArrayList<>();
//用来返回答案的
for (int i = 1;i <= nums.length ; i++) {
//遍历看哪些数是没有出现过的
if(!hmap.containsKey(i))
{
ans.add(i);
}
}
return ans;
}
}