# 一个有序数组数组，给出和为s的两个数字和连续正数数列

package java_study.JianZhiOffer;

import org.junit.Test;

/**
* Created by ethan on 2015/7/7.
* 剑指offer的No41 一个有序数组数组，给出和为s的两个数字和连续正数数列
*/
public class No41和为s的两个数字和连续正数数列 {

public void getPairsWithSumS(int[] arr, int s){
if (arr == null) return;
int start = 0;
int end = arr.length-1;
while (start<end){
if (arr[start]+arr[end]==s){
System.out.println(arr[start]+ " " + arr[end]);
start++;
}
else if(arr[start]+arr[end]>s)
end--;
else
start++;
}
}

public void getSeqenceWithSumS(int[] arr, int s){
if (arr == null) return;
if (arr.length == 1) return;
int start = 0;
int end = 1;
int sum = arr[start] + arr[end];
while (end<arr.length){
if (sum==s){
getPrintln(arr, start, end);
sum -= arr[start];
start++;
}else if (sum<s){
end++;
if (end>=arr.length)
return;
sum += arr[end];
}else {
sum -= arr[start];
start++;
}
}
}
public void getPrintln(int[] arr, int start, int end){
for (int i=start; i<=end; i++){
System.out.print(arr[i] + " ");
}
System.out.println();
}

@Test
public void test(){
int[] arr = {1,2,4,7,11,15};
getPairsWithSumS(arr, 15);
int[] arr1 = {1,2,3,4,5};
getSeqenceWithSumS(arr1, 9);
}
}


04-26 598

03-17 18

05-05 634

01-25 860

01-04 1398

#### java <em>数组</em>中<em>两个数</em>的和 等于另一个数<em>x</em>

2018年05月07日 00:00

10-01 953

11-17 331

03-04 1937

04-09 1.4万