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

后端 未结 8 2106
醉梦人生
醉梦人生 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.

提交回复
热议问题