给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
示例:
输入:
[4,3,2,7,8,2,3,1]
输出:
[5,6]
思路:
用哈希表存储nums中的元素,最后从1开始for循环去遍历哈希表,把哈希表中没出现的数字放到一个数组中,最后返回数组即可,时间复杂度O(n),空间复杂度O(n)
代码(HashMap) java
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
HashMap<Integer,Boolean> hashmap = new HashMap<Integer,Boolean>();
List<Integer> list = new ArrayList<Integer>();
for(int i : nums){
if(!hashmap.containsKey(i)){
hashmap.put(i,true);
}
}
for(int i = 1;i <= nums.length;i++){
if(!hashmap.containsKey(i)){
list.add(i);
}
}
return list;
}
}
代码(HashSet)java
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
HashSet<Integer> hashset = new HashSet<Integer>();
List<Integer> list = new ArrayList<Integer>();
for(int i : nums){
hashset.add(i);
}
for(int i = 1;i <= nums.length;i++){
if(!hashset.contains(i)){
list.add(i);
}
}
return list;
}
}
别人的解题思路:
遍历nums,把nums[i]当作下表,把对应下标num[i] - 1的位置上的元素取负数,这样遍历下来仍为正数的元素的下标就是nums缺少的元素
代码 java
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> list = new ArrayList<Integer>();
for(int i : nums){
nums[Math.abs(i) - 1] = -Math.abs(nums[Math.abs(i) - 1]);
}
for(int i = 0;i < nums.length;i++){
if(nums[i] > 0){
list.add(i + 1);
}
}
return list;
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。