Determine whether or not there exist two elements in Set S whose sum is exactly x - correct solution?

后端 未结 8 2072
醉梦人生
醉梦人生 2020-12-04 19:48

Taken from Introduction to Algorithms

Describe a Θ(n lg n)-time algorithm that, given a set S of n integers and another integer x, determines whet

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 20:21

    1. This is correct; your algorithm will run in O(n lg n) time.

    2. There is a better solution: your logic for calculating diff is incorrect. Regardless of whether a[i] is greater than or less than val, you still need diff to be val - a[i].

提交回复
热议问题