Find missing numbers in an array

Given an array nums of n integers, where nums[i] is in the interval

[1, n]. Please find all the numbers in the range [1, n] but not in nums, and return the result in the form of an array.

Example 1:

Input: nums = [4,3,2,7,8,2,3,1]

Output: [5,6]

what is it thinking

Let's first look at the idea of ​​the topic; problem-solving analysis, the red arrow marked below is the number marked as 1 because of the existence of the array 1-n

The unmarked number corresponding to the subscript of the array plus 1 is the number that disappears.

Next, we extend the following idea based on the above idea, mark the original array, we use negative numbers to mark, we must keep in mind that the negative number symbol is only used for marking, when extracting, just extract the number inside ;

Ok, now let's look at the final code

public class FindDisappearedNumbers448 {
    public static void main(String[] args) {
        int[] nums = {1,3,4,1};
        FindDisappearedNumbers448 fdn = new FindDisappearedNumbers448();
        fdn.findDisappearedNumbers(nums);
    }
    public List<Integer> findDisappearedNumbers(int[] nums) {
        for (int i = 0; i < nums.length; i++){
            int x = nums[i] >0 ? nums[i] : -nums[i];/*首先判断获得的数是否大于0,不大于0则取反取正数*/
                if (nums[x-1]>0){/*判断获得的数组下标-1的数是否大于零,如果大于零则没有标记,进行负数标记,反之被标记直接跳过*/
                    nums[x-1] = -nums[x-1];
                }
        }
        List<Integer> ret = new ArrayList<>();/*创建新数组,准备存值*/
        for (int i = 0; i < nums.length; i++){
            if (nums[i]>0){/*找到还有存在未标记的数组,大于零的数就是未标记的数,找到对应的数组下标,进行加1存值*/
                ret.add(i+1);
            }
        }
        return ret;
    }
}

Guess you like

Origin blog.csdn.net/m0_56550199/article/details/129752373