题目
给你一个含 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]
题解
找到数组中消失的数字
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
int n = nums.length;
for(int i = 0;i<n;i++){
int index = Math.abs(nums[i]) - 1; //当前元素应该对应的索引,可能有重复值已经标记会变负要用绝对值
if(nums[index]>0) nums[index] *= -1; //没被标记标记一下
}
List<Integer> result = new ArrayList<>();
for(int i = 0;i<n;i++){
if(nums[i]>0) result.add(i+1);
}
return result;
}
}
