题目
给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
示例:
输入:
[4,3,2,7,8,2,3,1]
输出:
[5,6]
解题
- 首先遍历一次数组, 遍历过程中将, nums[nums[i] - 1]的值变为复数, 数组中所有负数的下标值+1的数字, 都是1-n中已经出现过的数字
- 再遍历一次数组, 如果数组值是正数, 表示i + 1这个数字没有出现过, 添加到结果数组中即可, 遍历完成就得到解答了, 代码如下 :
class Solution { public List<Integer> findDisappearedNumbers(int[] nums) { List<Integer> indexs = new ArrayList<>(); int m; for(int i = 0; i < nums.length; i++){ m = Math.abs(nums[i]) - 1; if(nums[m] > 0){ nums[m] = -nums[m]; } } for(int i = 0; i < nums.length; i++){ if(nums[i] > 0){ indexs.add(i + 1); } } return indexs; }
}
```