【Offer】[57-1] 【和为S的两个数字】

题目描述

  输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,则输出任意一对即可。
  

牛客网刷题地址

思路分析

设置两个指针分别指向数组的头和尾,比较指定的sum和两个指针所指数值之和curSum的大小,如果相等,添加到list中,

  1. 如果sum<curSum ,因为数组是递增排序的,所以end指向的是元素中最大元素,如果要使sum==curSum,就要将头指针向后移动,才有可能满足sum==curSum,
  2. 否则,尾指针向前移动

测试用例

  1. 功能测试:数组中存在和为s的两个数;数组中不存在和为s的两个数。
  2. 特殊输入测试:表示数组的指针为nullptr指针。

Java代码

public class Offer057_01 {
    public static void main(String[] args) {
        test1();
        test2();
        test3();
        
    }

     public static ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {
        return Solution1(array,sum);
    }


    private static ArrayList<Integer> Solution1(int[] array, int sum) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        if(array.length<2 || array==null) {
            return list;
        }
        
        int start = 0;
        int end = array.length-1;
    
        while(start < end) {
            int curSum = array[start] + array[end];
            if(curSum==sum) {
                
                list.add(array[start]);
                list.add(array[end]);
                return list;
            }else if(curSum < sum) {
                start++;
            }else {
                end--;
            }
        }
        
        return list;
    
    }

    private static void test1() {
    }

    private static void test2() {

    }
    private static void test3() {

    }

}

代码链接

剑指Offer代码-Java

原文地址:https://www.cnblogs.com/haoworld/p/boffer571-he-weis-de-liang-ge-shu-zi.html