How to write the code with less time complexity for finding the missing element in given array range?

后端 未结 6 1992
一向
一向 2021-02-02 18:34

My function should return the missing element in a given array range. So i first sorted the array and checked if the difference between i and i+1 is not equal to 1, i\'m returni

6条回答
  •  北海茫月
    2021-02-02 18:51

    You could use a single loop approach by using a set for missing values.

    In the loop, delete each number from the missing set.

    If a new minimum value is found, all numbers who are missing are added to the set of missing numbers, except the minimum, as well as for a new maximum numbers.

    The missing numbers set contains at the end the result.

    function getMissing(array) {
        var min = array[0],
            max = array[0],
            missing = new Set;
        
        array.forEach(v => {
            if (missing.delete(v)) return;                   // if value found for delete return
            if (v < min) while (v < --min) missing.add(min); // add missing min values
            if (v > max) while (v > ++max) missing.add(max); // add missing max values
        });
        return missing.values().next().value;                // take the first missing value
    }
    
    console.log(getMissing([2, 3, 1, 5]));
    console.log(getMissing([2, 3, 1, 5, 4, 6, 7, 9, 10]));
    console.log(getMissing([3, 4, 5, 6, 8]));

提交回复
热议问题