题解 | #不重复打印排序数组中相加和为给定值的所有二元组#
不重复打印排序数组中相加和为给定值的所有二元组
http://www.nowcoder.com/practice/1ff1a607c81748baa1823ffa687d74c4
public class Main {
public static void printUniquePair(int[] arr, int k) {
if (arr == null || arr.length < 2) {
return;
}
int left = 0;
int right = arr.length - 1;
while (left < right) {
if (arr[left] + arr[right] < k) {
left++;
} else if (arr[left] + arr[right] > k) {
right--;
} else {
if (left == 0 || arr[left - 1] != arr[left]) {
System.out.println(arr[left] + "," + arr[right]);
}
left++;
right--;
}
}
}
public static void main(String[] args) {
int sum = 10;
int[] arr1 = { -8, -4, -3, 0, 1, 2, 4, 5, 8, 9 };
printArray(arr1);
System.out.println("====");
printUniquePair(arr1, sum);
}
}