和为S的连续正数序列
a为1,b为2。如果a+b的值小于s,那么b++,如果a+b的值大于s那么a++
public class Solution {
ArrayList<ArrayList<Integer> > list = new ArrayList<ArrayList<Integer>>();
public void numberSeqSum(int sum){
if(sum==0) System.out.println("no");
int small = 1;
int big = 2;
int mid = (sum+1)/2;//至少两个数
int total = small+big;
while(small<mid&&small<big){
if(total==sum){
ArrayList<Integer> l = new ArrayList<Integer>();
for(int i=small;i<=big;i++){
l.add(i);
}
list.add(l);
//System.out.println(small+" "+big);
big++;
total = total+big;
}else if(total < sum){
big++;
total = total + big;
}else{
total = total - small;
small++;
}
}
}
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
if(sum==1||sum==2) return list;
numberSeqSum(sum);
return list;
}
}
和为s的两个数字
输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
public class Solution {
public ArrayList<Integer> FindNumbersWithSum(int [] s,int target) {
ArrayList<Integer> list = new ArrayList<Integer>();
if(s.length==0) return list;
int a=0;int b=s.length-1;
while(a<b){
int sum = s[a] + s[b];
if(sum==target) break;
else if(sum>target) b--;
else a++;
}
if(a==b){
return list;
}
list.add(s[a]);
list.add(s[b]);
return list;
}