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

前端 未结 5 580
心在旅途
心在旅途 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 11:49

    Your algorithm is O(n log n). Each time you either divide 1st array size by two or do a binary search on the second one. This is O((log n) ^2) worst case (ie. S = {1,2...,n} and x = 0) and hence it's absorbed by sorting.

    Anyway you can do it a bit easier in O(n log n) by:

    1. sorting the array (O(n log n))
    2. iterating it's elements (O(n)) while in each iteration binary searching (O(log n)) for X-complement of the current element.

    edit: In response to your first question. x is the sum you're looking for and y are the elements of the input set. So if S= {y_1, y_2, y_3,..., y_n} then S' = {x - y_1, x - y_2, x - y_3, ...x - y_n}

提交回复
热议问题