// 题目1:输入一个递增排序的数组和一个sum值,输出数组中两个数和等于sum
public class Main {
public static void main(String[] args) throws Exception {
findSum(new int[]{1,2,4,7,11,15,17},18);
}
public static void findSum(int[] input, int sum) {
if(input.length == 0 || input.length == 1){
System.out.println("not found");
return;
}
int low = 0;
int high = input.length-1;
int resultCount = 0;
while(low<high){
if(input[low]+input[high] == sum){
System.out.println(input[low]+" "+input[high]);
high--;
resultCount++;
}else if(input[low]+input[high]>sum){
high--;
}else{
low++;
}
}
if(resultCount == 0){
System.out.println("not found");
}else{
System.out.println("found "+resultCount+" results");
}
}
}
//题目2:给出一个数s,打印出所有数字之和等于s的连续数字之和
public class Main {
public static void main(String[] args) throws Exception {
findSum2(15);
}
public static void findSum2(int sum) { //找出和为sum的所有序列
if(sum < 3){
System.out.println("sum is too small");
return;
}
int low = 1;
int high = 2;
while(low<=sum/2){
if(calSum(low,high) == sum){
printSeq(low,high);
high++;
}else if(calSum(low,high)>sum){
low++;
}else{
high++;
}
}
}
public static int calSum(int low, int high){ //计算序列数之和
int result = 0;
for(int i = low;i<=high;i++){
result += i;
}
return result;
}
public static void printSeq(int low, int high){ //打印序列结果
for(int i = low;i<=high;i++){
System.out.print(i+" ");
}
System.out.println();
}
}
剑指offer 41. 和为s的两个数字VS和为s的连续正数序列
最新推荐文章于 2024-09-16 20:08:29 发布