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

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

    Your solution seems fine. Yes you need to sort because its a pre requisite for binary search. You can make a slight modification to your logic as follows:

    public static boolean test(int[] a, int val) 
    {
        Arrays.sort(a);
    
        int i = 0;            // index of first element.
        int j = a.length - 1; // index of last element. 
    
        while(i val)
                j--;
            // else if sum is less than val, increase the sum.
            else
                i++;
        }
        // failed to find any such pair..return false. 
        return false;
    }
    

提交回复
热议问题