每日一题--和为s的两个数||和为s的连续整数列
2017-09-15 13:30
134 查看
和为s的两个数:时间复杂度o(n)
和为s的连续整数列(至少有两个整数),则small最大不超过(s+1)/2,输出多个结果
与上面题目思路一样:设置small和big,big往后加,大的话就减去small,让small向后移动
package core; /** 和为s的两个数字,输入数组为递增的 * Created by lxq on 2017/9/15. */ public class Problem5 { public static void main(String[] args){ Problem5 problem5 = new Problem5(); int[] array = {1,2,4,6,7}; problem5.findNumberWithSum(array,11); } public boolean findNumberWithSum(int[] array,int sum){ boolean find = false; if(array==null) return find; int number1 = 0; //结果 int number2 = 0; //结果 int start = 0; int end = array.length-1; while (start<end){ int curSum = array[start]+array[end]; if(curSum==sum){ number1 = array[start]; number2 = array[end]; find = true; break; }else if(curSum>sum){ end--; }else { start++; } } System.out.println(number1); System.out.println(number2); return find; } }
和为s的连续整数列(至少有两个整数),则small最大不超过(s+1)/2,输出多个结果
与上面题目思路一样:设置small和big,big往后加,大的话就减去small,让small向后移动
package core; /**输出所有和为s的连续整数序列(最少有两个数字) * Created by lxq on 2017/9/15. */ public class Problem6 { public static void main(String[] args){ Problem6 problem6 = new Problem6(); problem6.findContinueSequence(9); } public void findContinueSequence(int sum){ if(sum<3) return; int small = 1; int big = 2; int middle = (sum+1)/2; int curSum = small + big; //至少含有两个数字 while(small<middle){ if(curSum==sum) { //打印从small到big的数字 printContinueNum(small, big); } while (curSum>sum&&small<middle){ //先将值减去,再变small值 curSum -= small; small++; if(curSum==sum) printContinueNum(small,big); } //再增加big值,继续前面的过程,寻找更多的序列 //先变big值,再将值加上 big++; curSum+=big; } } private void printContinueNum(int small, int big) { for(int i = small;i<=big;i++){ System.out.println(i+" "); } System.out.println(); } }
相关文章推荐
- 面试题41:和为s的两个数字 VS 和为s的连续正整数序列
- 一个无序整数数组中找到最长连续序列(Longest Consecutive Sequence)和两个元素使得相差最小
- 剑指offer 面试题41 递增数组中和为s的两个数字 | 和为s的连续整数序列
- C#实现用欧几里德算法、连续整数检测算法、公因数算法求两个非负整数的最大公约数
- 算法基础:整数排序问题(连续整数仅仅保留首尾两个数字)
- 和为S的两个数字 and 和为s的连续正整数序列
- 每日一道算法题:输出和为n的连续正整数序列
- 大于6的连续3个整数, a, b, c, 其中两个是素数, 证明第三个能被6整除
- 和为s的两个数字VS和为s的连续整数序列
- 面试题 41 和为s的两个数字VS 和为S的连续整数序列
- [剑指offer]和为s的两个数 ; 和为s的连续正整数序列
- java每日一题:给定一个整数数组arr和整数target,返回两个索引值,使得这两个索引值对应的整数的和等于target。(arr中有且仅有一组)
- 和为s的两个数字VS和为s的连续整数序列(面试题 41)
- 每日一个C++小程序(十一)--两个整数、实数、复数的相加
- 面试题41:和为S的两个数字和为S的连续整数序列
- 每日一题(62) - 和为s的连续正整数序列
- 算法基础:整数排序问题(连续整数只保留首尾两个数字)
- c语言:输入两个整数m和n,计算需要改变m的二进制表示中的多少位才能得到n
- 每日一题(14)——找到符合要求的整数
- 每日一算--求两个数组的交集