有序数组的两数和

题目描述:在有序数组中找出两个数,使它们的和为指定的值,然后返回这两个数在原数组中的位置。

题目分析:使用双指针,一个指针指向值较小的元素,一个指针指向值较大的元素。指向较小元素的指针从头向尾遍历,指向较大元素的指针从尾向头遍历。

  • 如果两个指针指向元素的和 sum == target,那么得到要求的结果;
  • 如果 sum > target,移动较大的元素,使 sum 变小一些;
  • 如果 sum < target,移动较小的元素,使 sum 变大一些。

代码如下:

public class DoublePointer {
    public static void main(String[] args){
        int[] arr = {2,3,5,8,9,12,15,21};
        int target = 20;
        print(twoSum(arr, target));
    }

    public static int[] twoSum(int[] arr, int target) {
        int i = 0, j = arr.length - 1;
        while (i < j) {
            int sum = arr[i] + arr[j];
            if (sum == target) {
                return new int[]{i + 1, j + 1};
            } else if (sum < target) {
                i++;
            } else {
                j--;
            }
        }
        return null;
    }

    public static void print(int[] arr){
        System.out.print("[");
        for (int i = 0; i < arr.length; i++){
            if (i!=arr.length-1){
                System.out.print(arr[i] + ",");
            }else{
                System.out.print(arr[i]);
            }

        }
        System.out.print("]");
    }
}

执行结果:[3,7]

原文地址:https://www.cnblogs.com/earthhouge/p/10070773.html