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

后端 未结 6 2170
一向
一向 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:59

    Instead of sorting, you could put each value into a Set, find the minimum, and then iterate starting from the minimum, checking if the set has the number in question, O(N). (Sets have guaranteed O(1) lookup time)

    const input1 = [2, 3, 1, 5];
    const input2 = [2, 3, 1, 5, 4, 6, 7, 9, 10];
    const input3 = [3, 4, 5, 6, 8];
    
    function findMissing(arr) {
      const min = Math.min(...arr);
      const set = new Set(arr);
      return Array.from(
        { length: set.size },
        (_, i) => i + min
      ).find(numToFind => !set.has(numToFind));
    }
    console.log(findMissing(input1));
    console.log(findMissing(input2));
    console.log(findMissing(input3));

提交回复
热议问题