面试题41:和为s的两个数VS和为s的连续正数数列
来源:互联网 发布:美国动画 知乎 编辑:程序博客网 时间:2024/05/22 10:39
问题说明:
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;}}
0 0
- 面试题41:和为s的两个数VS和为s的连续正数数列
- 【剑指offer】面试题41-和为S的两个数VS和为S的连续正数序列
- 剑指offer面试题[41]-和为s的两个数VS和为s的连续正数序列
- 【面试题】和为S的两个数、和为S的连续正数序列
- 剑指offer面试题41和为s的两个数字VS和为s的连续正数序列
- [剑指offer][面试题41]和为s的两个数字 VS 和为s的连续正数序列
- 面试题41:和为s的两个数字VS和为s的连续正数序列
- 面试题41:和为s的两个数字VS和为s的连续正数序列
- 剑指offer 面试题41—和为s的两个数字VS和为s的连续正数序列
- 【剑指Offer学习】【面试题41:和为s 的两个数字vs 和为s 的连续正数序列】
- 面试题41和为S的两个数字VS和为s的连续正数序列
- 剑指offer-面试题41:和为s的两个数字VS和为s的连续正数序列
- 剑指offer之面试题41和为s的两个数字VS和为s的连续正数序列
- 面试题41:和为s的两个数字 VS 和为s的连续正数序列
- 面试题41:和为s的两个数字VS和为s的连续正数序列
- 剑指offer--面试题41:和为S的两个数字 vs 和为S的连续正数序列
- 剑指Offer-面试题41-和为s 的两个数字vs 和为s 的连续正数序列
- 剑指offer-面试题41-和为s的两个数字VS和为s的连续正数序列
- 文献检索方法,如何确定被ei收录,如何确定被sci收录,被引用次数
- ios 单列模式
- 导致QTP运行缓慢的常见原因
- 小算法
- c# 获取项目的根目录
- 面试题41:和为s的两个数VS和为s的连续正数数列
- 打印程序编译时间
- NO4.java学习笔记(数组、数组的操作【遍历、排序、查找】)
- 解题报告之——是不是树?
- 澄清鸡蛋的十大误传 帮助你更好的食用挑选鸡蛋
- dummy
- 今天配置了struts 2.3.16 发现需要引用9个jar包
- 结构体定义容易混淆的地方
- 边缘检测