您的解决方案似乎很好。是的,您需要排序,因为它是二进制搜索的先决条件。您可以对逻辑进行如下修改:
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<j) { // check if the sum of elements at index i and j equals val, if yes we are done. if(a[i]+a[j] == val) return true; // else if sum if more than val, decrease the sum. else if(a[i]+a[j] > val) j--; // else if sum is less than val, increase the sum. else i++; } // failed to find any such pair..return false. return false;}


