排序数组中寻找和的因子
题目描述
给定已排序数组arr和k,不重复打印arr中所有相加和为k的不降序二元组
如输入arr={-8,-4,-3,0,2,4,5,8,9,10};k=10;
输出(0,10)(2,8)
- 思路1:遍历数组每个元素,用二分查找寻找k-arr[i]
- 思路2:双指针逼近法
下面提供思路2的源代码
public class 排序数组中找和的因子_02 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int k = 10;
int[] arr = { -8, -4, -3, 0, 2, 4, 5, 8, 9, 10 };
int scannerPosition_01 = 0;
int scannerPosition_02 = arr.length - 1;
while (scannerPosition_01 < scannerPosition_02) {
int val = arr[scannerPosition_01] + arr[scannerPosition_02];
if (val > k) {// 右指针偏右
scannerPosition_02--;
} else if (val < k) {
scannerPosition_01++;
} else {
System.out.println("(" + arr[scannerPosition_01] + "," + arr[scannerPosition_02] + ")");
scannerPosition_01++;
}
}
}
}
扩展
三元组呢?
源代码
public class 排序数组中找和的因子之三元组 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int k = 10;
int[] arr = { -8, -4, -3, 0, 2, 4, 5, 8, 9, 10 };
for (int i = 0; i < arr.length; i++) {
int x = k - arr[i];
int scannerPosition_01 = i + 1;
int scannerPosition_02 = arr.length - 1;
while (scannerPosition_01 < scannerPosition_02) {// 查找值为x的二元组
int val = arr[scannerPosition_01] + arr[scannerPosition_02];
if (val > x) {// 右指针偏右
scannerPosition_02--;
} else if (val < x) {
scannerPosition_01++;
} else {
System.out.println(
"(" + arr[i] + "," + arr[scannerPosition_01] + "," + arr[scannerPosition_02] + ")");
scannerPosition_01++;
}
}
}
}
}