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.

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

class Solution {
    // public List findDisappearedNumbers(int[] nums) {
    //     int n = nums.length;
    //     for(int num: nums){
    //         int x = Math.abs(num)-1;
    //         nums[x] = 0 - Math.abs(nums[x]);
    //     }
    //     List result = new ArrayList();
    //     for(int i=0; i 0){
    //             result.add(i+1);
    //         }
    //     }
    //     return result;        
    // }

    public List findDisappearedNumbers(int[] nums) {
        int n = nums.length;
        for(int num: nums){
            int x = (num - 1) % n;
            nums[x] += n;
        }
        List result = new ArrayList();
        for(int i=0; i