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

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

    If the array is items and the difference between missing and present diff is 1:

    const missingItem = items => [Math.min(...items)].map(min => items.filter(x =>
        items.indexOf(x-diff) === -1 && x !== min)[0]-diff)[0]
    

    would give complexity of O(n^2).

    It translates to: find the minimum value and check if there isn't a n-diff value member for every value n in the array, which is also not the minimum value. It should be true for any missing items of size diff.

    To find more than 1 missing element:

    ([Math.min(...items)].map(min => items.filter(x =>
        items.indexOf(x-diff) === -1 && x !== min))[0]).map(x => x-diff)
    

    would give O((m^2)(n^2)) where m is the number of missing members.

提交回复
热议问题