剑指offer-41.和为S的两个数字

https://www.nowcoder.com/practice/390da4f7a00f44bea7c2f3d19491311b?tpId=13&tqId=11195&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

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

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

题解:
利用数组有序的特性。
用两个指针,分别指向数组的头和尾。
如果头尾指针指向的数字的和为S,则输出;
如果和大于S,则尾指针向后移;
如果和小于S,则头指针向前移。
时间复杂度为 O(n)

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> FindNumbersWithSum(int[] array, int sum) {
        ArrayList<Integer> result=new ArrayList();
        if (array == null || array.length < 2) {
            return result;
        }
        int behind = 0;
        int ahead = array.length - 1;
        while (behind < ahead) {
            if((array[behind]+array[ahead])>sum){
                ahead--;
            }else if((array[behind]+array[ahead])<sum){
                behind++;
            }else{
                result.add(array[behind]);
                result.add(array[ahead]);
                break;
            }
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/zxm1306192988/article/details/81809930