1.题目描述
输入一个含 n 个整数的数组 nums ,其中 nums[i] 在区间 [1, n] 内。请你找出所有在 [1, n] 范围内但没有出现在 nums 中的数字,并以数组的形式返回结果。
2.示例
输入:nums = [5,3,2,6,8,2,3,1]
输出:[4,7]
该例子输入一个包含8位整数的数组nums,数组里每位对象的值都在区间[1,8]内,该数组经排序后为[1,2,2,3,3,5,6,8],缺少4和7两位整数。
3,做题思路
//方法一:利用Set:不包含重复元素的集合 //首先遍历一遍nums,并把数字都添加到set集合中 //然后再从1到n进行遍历,如果add(nums[i])成功,他会返回一个true的,成功那么给队列也执行一个add
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> res = new ArrayList<>();//创建一个集合来存储
HashSet<Integer> set = new HashSet<>();//创建一个Set集合的实现对象HashSet
for (int i = 0; i <nums.length; i++) {
set.add(nums[i]);//如果有了他就添加不进去,也不会报错的
}
for (int i = 1; i <= nums.length; i++) {
if(set.add(i)){
res.add(i);
}
}
return res;
}
}
//方法二:我们可以用一个哈希表记录数组 nums 中的数字,由于数字范围均在 [1,n] 中,
//记录数字后我们再利用哈希表检查[1,n] 中的每一个数是否出现,从而找到缺失的数字。
//由于数字范围均在 [1,n] 中,我们也可以用一个长度为 n 的数组来代替哈希表。
//这一做法的空间复杂度是 O(n) 的。我们的目标是优化空间复杂度到 O(1)。
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
Map<Integer,Integer> zs=new HashMap<>();
//题目说以数组形式返回
//我就写了个int [] res= new int[n];//会报错
//得用List来做返回,这个点得注意,应该是返回的结果必须的变长的
List<Integer> res=new ArrayList<>();
for(int i=0;i<nums.length;i++){
if(!zs.containsKey(nums[i])){
//哈希表的装入是put,一开始写成了add
zs.put(nums[i],nums[i]);
}
}
//这个for循环一开始我写的是k<=n;因为是从1到n遍历嘛,后面才发现,没有n传送过来的,题目说的n是长度,得用length获得
for(int k=1;k<=nums.length;k++){
if(!zs.containsKey(k)){
res.add(k);
}
}
return res;
}
}
//方法三:
//因为nums的长度恰好为n,nums的数字范围也在[1,n]之间,可以利用这个数字范围之外的数字来表达是否存在。具体怎么操作呢?
//我们首先遍历nums,每遇到一个数x,就让nums[x-1]+n,因为nums数组中的元素范围,所以加n以后,这些数肯定都大于n
//最后我们遍历nums[i],如果不大于n,就说明没遇到过数i+1,也就找到了缺失的数字
//这个巧妙之处在于,存储的时候就是存到对应的x-1的下标位置处
//而且有的数可能出现两次,就应该对这个数去进行%n处理,下面代码的做法是存储的时候,遍历的时候就拿到一个数先%n,因为都小于n嘛,加过n的自然可以模掉
//我想的是可以在往ret集合存储的时候%n,也就是ret.add((i%n)+1),应该是这两种方式都ok
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
int n = nums.length;
for (int num : nums) {
int x = (num - 1) % n;//对n取模拿到他原来的值
nums[x] += n;//注意此处的nums[x],跟解释处的nums[x-1]是对应的,代码中的num是上面解释中的x
}
List<Integer> ret = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
if (nums[i] <= n) {
ret.add(i + 1);//如果没被遍历过的就把i+1存到集合中等待返回
}
}
return ret;
}
}
4,调用方式
在主类Main中调用
public class Main { public static void main(String[] args) { Solution solution = new Solution(); int[] nums = {5,3,2,6,8,2,3,1}; System.out.println(solution.findDisappearedNumbers(nums)); } }