[LeetCode] 448. 找到所有数组中消失的数字(思维)

题目

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

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

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

示例:

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

输出:
[5,6]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

  • 从题目“给定一个范围在  1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组”数组值的范围,应该想到数组值可以做数组索引,这个方法经常会用到。
  • 第一遍将遇到的数(再-1,再取绝对值因为可能已经被更改为负)对应的数组索引的数置为负数(不能简单取反而是置为负),那么第二遍看还是正数的索引(+1)即是缺失的数。

代码

class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        List<Integer> list = new LinkedList<>();
        for (int i = 0; i < nums.length; ++i) {
            int idx = Math.abs(nums[i]) - 1;  //
            if (nums[idx] > 0) { //
                nums[idx] = -nums[idx];
            }
        }
        for (int i = 0; i < nums.length; ++i) {
            if (nums[i] > 0) {
                list.add(i + 1);
            }
        }
        return list;
    }
}

猜你喜欢

转载自www.cnblogs.com/coding-gaga/p/11741376.html