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