448. 找到所有数组中消失的数字
难度简单1170收藏分享切换为英文接收动态反馈
给你一个含 n
个整数的数组 nums
,其中 nums[i]
在区间 [1, n]
内。请你找出所有在 [1, n]
范围内但没有出现在 nums
中的数字,并以数组的形式返回结果。
示例 1:
输入:nums = [4,3,2,7,8,2,3,1]
输出:[5,6]
示例 2:
输入:nums = [1,1]
输出:[2]
提示:
-
n == nums.length
-
1 <= n <= 105
-
1 <= nums[i] <= n
进阶:你能在不使用额外空间且时间复杂度为 O(n)
的情况下解决这个问题吗? 你可以假定返回的数组不算在额外空间内。
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
// Hash table for keeping track of the numbers in the array
// Note that we can also use a set here since we are not
// really concerned with the frequency of numbers.
HashMap<Integer, Boolean> hashTable = new HashMap<Integer, Boolean>();
// Add each of the numbers to the hash table
for (int i = 0; i < nums.length; i++) {
hashTable.put(nums[i], true);
}
// Response array that would contain the missing numbers
List<Integer> result = new LinkedList<Integer>();
// Iterate over the numbers from 1 to N and add all those
// that don't appear in the hash table.
for (int i = 1; i <= nums.length; i++) {
if (!hashTable.containsKey(i)) {
result.add(i);
}
}
return result;
}
}