码迷,mamicode.com
首页 > 编程语言 > 详细

有序数组的两数和

时间:2018-12-05 16:26:57      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:str   stat   分析   pre   --   col   epo   使用   get   

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

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

  • 如果两个指针指向元素的和 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]

有序数组的两数和

标签:str   stat   分析   pre   --   col   epo   使用   get   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!