和为S的两个数字

题目描述

输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。

输出描述:

对应每个测试案例,输出两个数,小的先输出。

思路一:
在第一个第二个位置搞两个指针,首先让第二个指针走到满足条件的最大位置,就是刚刚大于或等于S的位置,之后就是首位一次递加递减来判断。

public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {
    ArrayList<Integer> res = new ArrayList<Integer>();
    if(array.length < 2) return res;
    int start =0,end=1;
    int total = array[start] + array[end];
    boolean isMaxEnd = false;
    while(start < end){
        if(total == sum){
            if(res.isEmpty()) {
                res.add(array[start]);
                res.add(array[end]);
            } else {
                int multi = res.get(0) * res.get(1);
                if(multi > (array[start]*array[end])){
                    res.clear();
                    res.add(array[start]);
                    res.add(array[end]);
                }
            }
            start++;
            total = array[start] + array[end];
        } else if(total < sum){
            if(!isMaxEnd)
                end++;
            else
                start++;
            total = array[start] + array[end];
        } else if(total > sum) {
            isMaxEnd = true;
            end--;
            total = array[start] + array[end];
        }
    }
    return res;
}

思路二:
数列满足递增,设两个头尾两个指针i和j,
若ai + aj == sum,就是答案(相差越远乘积越小
若ai + aj > sum,aj肯定不是答案之一(前面已得出 i 前面的数已是不可能),j -= 1
若ai + aj < sum,ai肯定不是答案之一(前面已得出 j 后面的数已是不可能),i += 1
O(n)

public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {
    ArrayList<Integer> res = new ArrayList<Integer>();
    if(array.length < 2) return res;
    int start = 0, end = array.length -1;
    while(start < end) {
        if(array[start] + array[end] == sum){
            res.add(array[start]);
            res.add(array[end]);
            break;
        } 
        else if (array[start] + array[end] > sum) 
            end--;
        else if (array[start] + array[end] < sum)
            start++;
    }
    return res;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值