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

后端 未结 8 2029
醉梦人生
醉梦人生 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:13

    I do think I have spotted a minor bug in your implementation, but testing should uncover that one quickly.

    The approach looks valid, and will reach the desired performance. You might simplify it by replacing the iterative binary search with a scan through the array, in effect replacing the binary search by a linear search that resumes where the previous linear search left off:

    int j = a.length - 1;
    for (int i = 0; i < a.length; i++) {
        while (a[i] + a[j] > val) {
            j--;
        }
        if (a[i] + a[j] == val) {
            // heureka!
        }
    }
    

    This step is O(n). (Proving that is left as an exercise for you.) Of course, the entire algorithm still takes O(n log n) for the merge sort.

    0 讨论(0)
  • 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].

    0 讨论(0)
提交回复
热议问题