LeetCode Daily Question 448. Find all the missing numbers in the array

448. Find all missing numbers in the array

Given an 1 ≤ a[i] ≤ ninteger array with a range of (n = array size), some elements in the array appear twice, and some only appear once.

Find all in [1, n]the range does not appear in the array of numbers.

Can you accomplish this task without using extra space and the time complexity is O(n)? You can assume that the returned array is not included in the extra space.

Example:

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

输出:
[5,6]

Method 1: Modify in situ

Problem-solving ideas

I thought it was a simple problem, and I could strike hard. After thinking about it for a long time, I haven't figured it out. After reading the official answer, I realized that the in- situ modification is not considered extra space ~

Reference Code

public List<Integer> findDisappearedNumbers(int[] nums) {
    
    
    List<Integer> ans = new ArrayList<>();
    int n = nums.length;
    for (int num : nums) {
    
    
        int x = (num - 1) % n;
        nums[x] += n;
    }
    for (int i = 0; i < n; i++) {
    
    
        if (nums[i] <= n) {
    
    
            ans.add(i + 1);
        }
    }
    return ans;
}

Results of the
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_27007509/article/details/113803855