[LeetCode] 448. Find All Numbers Disappeared in an Array
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.
找到所有数组中消失的数字。
给你一个含 n 个整数的数组 nums ,其中 nums[i] 在区间 [1, n] 内。请你找出所有在 [1, n] 范围内但没有出现在 nums 中的数字,并以数组的形式返回结果。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-all-numbers-disappeared-in-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
影子题442。题意也几乎一样。
注意这个题的范围也是从1到N,所以才能用442题的解法。442题是把遇到的数字当成坐标,去把对应坐标上的数字改成负数,如果再次遇到,则说明是重复数字;这个题的做法也是把遇到的数字当成坐标,把坐标映射到的数字改成负数,再遍历第二遍的时候,如果发觉某个数字没有被改成负数则说明第一次没有被遍历到,也说明他对应的index是缺失的。
时间O(n)
空间O(1) - required
Java实现
1 class Solution { 2 public List<Integer> findDisappearedNumbers(int[] nums) { 3 List<Integer> res = new ArrayList<>(); 4 for (int i = 0; i < nums.length; i++) { 5 int index = Math.abs(nums[i]) - 1; 6 if (nums[index] > 0) { 7 nums[index] = -nums[index]; 8 } 9 } 10 for (int i = 0; i < nums.length; i++) { 11 if (nums[i] > 0) { 12 res.add(i + 1); 13 } 14 } 15 return res; 16 } 17 }
相关题目
442. Find All Duplicates in an Array