LeetCode—448. Find All Numbers Disappeared in an Array—Analysis and Code (Java)

LeetCode-448. Find All Numbers Disappeared in an Array [Find All Numbers Disappeared in an Array]-Analysis and Code [Java]

1. Title

Given an integer array with a range of 1 ≤ a[i] ≤ n (n = array size), some elements in the array appear twice, and some only appear once.
Find all the numbers in the range [1, n] that do not appear in the array.
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]

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, analysis and code

1. Negative mark

(1) Thinking

Combining the characteristics of the question, the number range of the integer array is [1, n], and the subscript range of the array is [0, n-1], so you can directly mark the number of subscript +1 through the corresponding position of the subscript. .
In order to avoid interference to the untraversed numbers during the marking process, the number of the position to be marked can be selected as a negative value, which can record the existence of the number without affecting the subsequent traversal process.

(2) Code

class Solution {
    
    
    public List<Integer> findDisappearedNumbers(int[] nums) {
    
    
        List<Integer> ans = new ArrayList<>();
        if (nums.length == 0)
            return ans;
        
        for (int val : nums) {
    
    
            int num = (val > 0) ? val : -val;
            if (nums[--num] > 0)
                nums[num] = -nums[num];
        }

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

(3) Results

Execution time: 6 ms, beating 89.31% of users
in all Java submissions ; memory consumption: 48 MB, beating 27.98% of users in all Java submissions.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/112688695