Sword refers to Offer-39-two numbers whose sum is s

Title description

Input an ascending array and a number S, and find two numbers in the array so that their sum is exactly S. If the sum of multiple pairs of numbers is equal to S, output the smallest product of the two numbers.

Output description:

Corresponding to each test case, output two numbers, the smallest number is output first.

Idea analysis

Just finished one or more consecutive sums of sums, and then came up with a sum of two sums.
Violent resolution, two pointers, one from the front and one from the back. If the result of the sum is equal, it is added to the result. If the result is greater than sum, the pointer to the tail is reduced (the array is ordered, so the tail pointer becomes smaller to the left), and vice versa.

Code

import java.util.ArrayList;
public class Solution {
    
    
    public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {
    
    
          ArrayList<Integer> result = new ArrayList<Integer>();
        if(array == null || array.length == 0) return result;
        int i = 0;
        int j = array.length - 1;
        while(i<j){
    
    
            int temp = j;//展示存储j的值
            if(sum == (array[i] + array[j])){
    
    
                result.add(array[i]);
                result.add(array[j]);
                break;
            }else if(array[i]+array[j]<sum){
    
    
//                如果小于sum,且数组有序,说明应该增加小的值,
                i++;
            }else {
    
    
                //如果和大于sum,说明大的值大了,于是减小大的值
                j--;
            }
        }
        return result;
    }
}

Guess you like

Origin blog.csdn.net/H1517043456/article/details/107436969
Recommended