LeetCode-448-消失的数字

  |   0 评论   |   0 浏览

给定一个范围在  1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。

找到所有在 [1, n] 范围之间没有出现在数组中的数字。

您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。

示例:

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

输出:
[5,6]

解法

  1. 遍历每个元素,对索引进行标记
    • 将对应索引位置的值变为负数;
  2. 遍历下索引,看看哪些索引位置上的数不是负数的。
    • 位置上不是负数的索引,对应的元素就是不存在的。
 public List<Integer> findDisappearedNumbers(int[] nums) {
        List<Integer> res = new ArrayList<>();
        for(int num: nums) {
            int index = Math.abs(num) - 1;
            if (nums[index] > 0) {
                nums[index] = nums[index] * -1;
            }
        }

        for(int i = 0; i < nums.length; i++) {
            if(nums[i] > 0) {
                res.add(i + 1);
            }
        }
        return res;
    }

运行

image.png


标题:LeetCode-448-消失的数字
作者:guobing
地址:http://www.guobingwei.tech/articles/2021/01/07/1609981990344.html