来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array

描述

给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。

示例:
输入:
[4,3,2,7,8,2,3,1]

输出:
[5,6]

题解

  1. class Solution {
  2. public List<Integer> findDisappearedNumbers(int[] nums) {
  3. for (int i = 0; i < nums.length; i++) {
  4. int newIndex = Math.abs(nums[i]) - 1;
  5. if (nums[newIndex] > 0) {
  6. nums[newIndex] *= -1;
  7. }
  8. }
  9. List<Integer> res = new ArrayList<>();
  10. for (int i = 1; i <= nums.length; i++) {
  11. if (nums[i - 1] > 0) {
  12. res.add(i);
  13. }
  14. }
  15. return res;
  16. }
  17. }

复杂度分析

  • 时间复杂度 : 448. 找到所有数组中消失的数字(Find All Numbers Disappeared in an Array) - 图1
  • 空间复杂度 : 448. 找到所有数组中消失的数字(Find All Numbers Disappeared in an Array) - 图2。因为我们在原地修改数组,没有使用额外的空间。