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

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

    Found this old question and wanted to take a stab at it. I had a similar thought to https://stackoverflow.com/users/2398764/koushik-chatterjee in that I think you can optimize this by knowing that there's always only going to be one missing element. Using similar methodology but not using a max will result in this:

    function getMissing(arr) {
        var sum = arr.reduce((a, b) => a + b, 0);
        var lowest = Math.min(...arr);
        var realSum = (arr.length) * (arr.length + 1) / 2 + lowest * arr.length;
        return realSum - sum + lowest;
    }
    

    With the same inputs as above. I ran it in jsperf on a few browsers and it is faster then the other answers.

    https://jsperf.com/do-calculation-instead-of-adding-or-removing.

    First sum everything, then calculate the lowest and calculate what the sum would be for integers if that happened to be the lowest. So for instance if we have 2,3,4,5 and want to sum them that's the same as summing 0,1,2,3 and then adding the lowest number + the amount of numbers in this case 2 * 4 since (0+2),(1+2),(2+2),(3+2) turns it back into the original. After that we can calculate the difference but then have to increase it once again by the lowest. To offset the shift we did.

提交回复
热议问题