Find the minimum number of elements required so that their sum equals or exceeds S

前端 未结 5 1358
你的背包
你的背包 2021-02-05 11:46

I know this can be done by sorting the array and taking the larger numbers until the required condition is met. That would take at least nlog(n) sorting time.

Is there a

5条回答
  •  Happy的楠姐
    2021-02-05 12:49

    Assuming the numbers are integers, you can improve upon the usual n lg(n) complexity of sorting because in this case we have the extra information that the values are between 0 and S (for our purposes, integers larger than S are the same as S).

    Because the range of values is finite, you can use a non-comparative sorting algorithm such as Pigeonhole Sort or Radix Sort to go below n lg(n).

    Note that these methods are dependent on some function of S, so if S gets large enough (and n stays small enough) you may be better off reverting to a comparative sort.

提交回复
热议问题