原创转载请注明出处:http://agilestyle.iteye.com/blog/2361909
Question
Print all pairs of values a sorted array that sum up to a given value M
Example
Solution
1. Scan from both ends, calculate the sum
2. if(sum is equal to M), print and shrink the focus window
3. if(sum is less than M), shift left focus index by 1
4. if(sum is bigger than M), shift right focus index by 1
5. Stop the loop when left is larger or equal to right index
package org.fool.java.test;
public class PrintAllPairsSumToM {
public static void main(String[] args) {
int[] sorted = {1, 2, 3, 4, 8, 9, 9, 10};
printAllPairs(sorted, 12);
}
private static void printAllPairs(int[] sorted, int m) {
int left = 0;
int right = sorted.length - 1;
while (left < right) {
int tempSum = sorted[left] + sorted[right];
if (tempSum == m) { // which means we find one pair
System.out.println("Sum of {" + sorted[left] + ", " + sorted[right] + "} = " + m);
// update the both index values
left++;
right--;
} else if (tempSum > m) { // which means the temp sum is bigger than m
right--; // shift right focus index by 1
} else { // which means the temp sum is smaller than m
left++; // shift left focus index by 1
}
}
}
}
Console Output

Reference
https://www.youtube.com/watch?v=l5orcTJlT54&list=PLlhDxqlV_-vkak9feCSrnjlrnzzzcopSG&index=39
寻找数组中和为M的对
本文介绍了一种高效算法来找出已排序数组中所有和等于特定值M的元素对。通过从数组两端开始扫描并逐步调整左右指针位置,可以在O(n)时间内找到所有符合条件的元素对。
842

被折叠的 条评论
为什么被折叠?



