O(n log(n)) algorithm that checks if sum of 2 numbers in a int[] = given number

前端 未结 5 609
心在旅途
心在旅途 2021-01-03 11:24

I am supposed to create a O(n log(n)) algorithm that checks if sum of 2 numbers in a int[] == given number.

eg. Given [1,4,7,2,3,4] there will be a sum

5条回答
  •  暖寄归人
    2021-01-03 12:11

    What they say is the following:
    S=[1,4,7,2,3,4]

    Sort S using mergesort you get Ss=[1,2,3,4,7]. Cost is O(nlogn) - just check wiki for this.

    Then you have x=8
    So you form S'=[7,6,5,4,1] by subtracting x with the elements in S.
    Sort S' using mergesort in O(nlogn)
    Remove duplicates requires O(n).

    Then you merge the Ss and S'.
    You check for duplicates in consecutive positions in O(n).
    Total is:
    O(nlogn)+O(nlogn)+O(n)+O(n)+O(n) = O(nlogn)

提交回复
热议问题