和为S的两个数字
输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
输出描述: 对应每个测试案例,输出两个数,小的先输出。
解题思路
数组是有序,在数组首尾各放入一指针,判断两指针的数的和是否与sum相等,如果小,plow向前进一步;如果大,phigh往后退一步。
代码
import java.util.ArrayList;
/**
* 剑指offer一刷:和为S的两个数字
*
* @author User
* @create 2019-05-30-15:25
*/
public class jzo42 {
public ArrayList<Integer> FindNumbersWithSum(int [] array, int sum) {
ArrayList<Integer> re=new ArrayList<>();
if (array==null||array.length<2){
return re;
}
int plow=0,phigh=array.length-1;
while (phigh>plow){
if (array[phigh]+array[plow]==sum){
re.add(array[plow]);
re.add(array[phigh]);
return re;
}else if (array[plow]+array[phigh]>sum){
phigh--;
}else{
plow++;
}
}
return re;
}
public static void main(String[] args){
int[] array={1,2,3,4,5,6,7,8,9};
int sum=7;
jzo42 so=new jzo42();
System.out.println(so.FindNumbersWithSum(array,sum));
}
}
和为S的连续正数序列
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
输出描述: 输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
解题思路
因为数组是有序的,可以使用动态指针法,两指针间的数和小于sum,,phigh++;如果大于sum,plow++
代码
import java.util.ArrayList;
/**
* 剑指offer一刷:和为S的连续正数序列
*
* @author User
* @create 2019-05-30-14:49
*/
public class jzo41 {
public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> res=new ArrayList<>(); //存放结果
int plow=1,phigh=2; //两个起点,间距表示窗口的大小
while (phigh>plow){
//由于是连续的,所以求和公式是(a0+an)*n/2
int cur=(phigh+plow)*(phigh-plow+1)/2;
//将结果加入结果集
if (cur==sum){
ArrayList<Integer> list=new ArrayList<>();
for (int i=plow;i<=phigh;i++){
list.add(i);
}
res.add(list);
plow++;
}else if (cur<sum){
phigh++;
}else {
plow++;
}
}
return res;
}
public static void main(String[] args){
int sum=15;
jzo41 so=new jzo41();
System.out.println(so.FindContinuousSequence(sum));
}
}