剑指offer 41. 和为s的两个数字VS和为s的连续正数序列

// 题目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();
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值