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

后端 未结 6 2000
一向
一向 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 19:02

    You can use while loop as well, like below -

    function getMissing(array) {
      var tempMin = Math.min(...array);
      var tempMax = tempMin + array.length;
      var missingNumber = 0;
      
      while(tempMin <= tempMax){
        if(array.indexOf(tempMin) === -1) {
           missingNumber = tempMin;
        }
        tempMin++;
      }
      return missingNumber;
    }
    
    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]));

提交回复
热议问题