问题说明:
1.和为s的两个数问题是从一个排序的数组中找出和为s的两个数;
2.原题是找出一个即可,现在全部找出;
3.和为s的连续正数数列是给定一个数找出所有连续正数数列的和为s,例如s为9,(2,3,4)就是其中一组。
(一)和为s的两个数问题
public static int findNumbersWithSum(int[] sorted, int fromIndex, int toIndex, int sum){
if(null == sorted || sorted.length == 0){
throw new IllegalArgumentException();
}
// allow one element in sorted but at least two elment to make a pair
if(fromIndex > toIndex){
throw new IndexOutOfBoundsException("fromIndex : " + fromIndex + "toIndex : " + toIndex);
}
int countPair = 0;// return value
int smallIndex = fromIndex;
int bigIndex = toIndex;
int currentSum = 0;
while(smallIndex < bigIndex){
currentSum = sorted[smallIndex] + sorted[bigIndex];
if(currentSum > sum){
bigIndex--;
}
if(currentSum < sum){
smallIndex++;
}
if(currentSum == sum){
int firstNotEqualSmall = smallIndex + 1;
while(firstNotEqualSmall < bigIndex && (sorted[firstNotEqualSmall] == sorted[smallIndex])){
firstNotEqualSmall++;
}
int firstNotEqualBig = bigIndex - 1;
while(firstNotEqualBig > smallIndex && (sorted[firstNotEqualBig] == sorted[bigIndex])){
firstNotEqualBig--;
}
//int equalSmallLen = firstNotEqualSmall - smallIndex;
//int equalBigLen = bigIndex - firstNotEqualBig;
// may be i == j so add condition by i < j
for(int i = smallIndex; i < firstNotEqualSmall; i++){
for(int j = bigIndex; (i < j) && (j > firstNotEqualBig); j--){
countPair++;
System.out.println("equal sum = " + sum + " pair index is (" + i + "," + j + ")"
+ " and value is (" + sorted[i] + "," + sorted[j] + ")");
}
}
// go on to find again
smallIndex = firstNotEqualSmall;
bigIndex = firstNotEqualBig;
}// end if ==
}//end while
return countPair;
}
(二)和为s的连续正数数列
public static void findContinousSequence(int sum){
if(sum < 3){
return ;
}
int small = 1;
int big = 2;
int currentSum = 3;
int middle = (1 + sum) >> 1;
while(small < middle){
if(currentSum == sum){
print(small, big);
}
while(currentSum > sum && small < middle){
currentSum -= small;
small++;
if(currentSum == sum){
print(small, big);
}
}
// maybe currentSum < sum or small >= middle
big++;
currentSum += big;
}
}