本文主要是介绍面试题41:和为s的两个数VS和为s的连续正数数列,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题说明:
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 pairif(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 < jfor(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 againsmallIndex = firstNotEqualSmall;bigIndex = firstNotEqualBig;}// end if ==}//end whilereturn 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 >= middlebig++;currentSum += big;}
}
这篇关于面试题41:和为s的两个数VS和为s的连续正数数列的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!