PHP algorithm Title: 448 find all the missing numbers in the array

Time:2020-7-20

448. Find all the missing numbers in the array

Title Link: https://leetcode-cn.com/probl…

Difficulty: simple

Title Description

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

Find all numbers in the range [1, n] that do not appear in the array.

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

Examples

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

Output:
[5,6]

thinking

Drawer principle: one radish, one pit

1.

Each element in the array has its corresponding array subscript (for example, element 2, whose corresponding array subscript is 1), and what we want to get is those array subscripts that are not matched by elements

/**
     *Drawer principle
     * @param Integer[] $nums
     * @return Integer[]
     */
    function findDisappearedNumbers($nums) {
        $len = count($nums);
        
        #Match the index with the array element
        #Relationship between subscript and element [element-1 = subscript]
        for($i=0;$i<$len;$i++){
            $index = ($nums[$i]-1)%$len;
            $nums[$index] += $len;
        }
        $res = [];
        #Grabs no matched subscripts
        for($i=0;$i<$len;$i++){
            if($nums[$i] <= $len){
                $res[] = $i+1;
            }
        }

        return $res;

    }

Recommended Today

Array of algorithms — sum of three numbers

Sum of three numbers difficultysecondary Here is an array of N integersnums, judgmentnumsAre there three elements a, B, C in a such that a + B + C = 0? Please find all triples that satisfy the condition and do not repeat.be careful:The answer cannot contain duplicate triples. Example:Given array nums = [- 1, 0, […]