题目描述
Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.
样例描述
Example 1:
Input: nums = [4,3,2,7,8,2,3,1]
Output: [5,6]
Example 2:
Input: nums = [1,1]
Output: [2]
Constraints:
n == nums.length
1 <= n <= 105
1 <= nums[i] <= n
Follow up: Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
思路
- 标记的思路,不用额外空间。将出现过的数对应的下标位置数置为负数,然后在扫描一遍,正数的位置对应的下标加1就是消失的数字
- 注意 下标从0开始,置负数时要减一,然后先取绝对值,遍历到这个数时可能该数被置为了负数。 最后,因为有的数出现多次,先判断该位置是否大于0,避免已经负数了又被重复置为正数
代码
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> res = new ArrayList<>();
//将出现过的数作为下标对应的数 置为负数
for (int x: nums){
//换绝对值,因为可能被置为负数了
x = Math.abs(x);
if (nums[x - 1] > 0) nums[x - 1] *= -1;
}
//寻找不是负数的就是消失的
for (int i = 0; i < nums.length; i ++){
//下标是0开始的,对应数要加一
if (nums[i] > 0) res.add(i + 1);
}
return res;
}
}