LeetCode刷题系列—167.Two Sum II - Input array is sorted 有序数组中求和为给定值的两个数

1 题目描述

1.1 英文描述

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

Note:

Your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution and you may not use the same element twice.

Example:

Input: numbers = [2,7,11,15], target = 9

Output: [1,2]

Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

1.2 中文描述

给你一个整数数组,并且这个数组是按递增排序的,你要找到数组中的两个整数,它们的和等于给定的目标值,然后返回它们的下标。

题目假设给你的数组总是有且只有一个解,而且同一个元素不能使用两次。另外,返回结果的下标要从 1 开始。

2 解法

2.1 解法1 - 二分查找

先循环确定一个数,另一个数在剩余的数中用二分查找出来。

    /**
     *  方式1:二分查找
     *  先循环确定一个数,
     *  另一个数在剩余的数中用二分查找出来。
     */
    public static int[] towSumII(int[] arr,int target){
     int[] answer = new int[2];

     ok : for(int i = 0;i < arr.length;i++){
         int left = i + 1;
         int right = arr.length - 1;

         while (left <= right){
             int mid = left + (right - left) / 2;
             if(arr[mid] + arr[i] > target){
                 right = mid - 1;
             }else if(arr[mid] + arr[i] < target){
                 left = mid + 1;
             }else if(arr[mid] + arr[i] == target){
                 answer[0] = i + 1;
                 answer[1] = mid + 1;
                 break ok;
             }
         }

     }

     return answer;
    }

2.2 解法2 - 双指针

1)初始化首指针指向首元素,尾指针指向尾元素。

2)如果首尾指针对应元素相加小于target,则首指针从左往右移动。

3)如果首尾指针对应元素相加大于target,则尾指针从右往左移动。

    /**
     *  方式2:双指针
     *  1)初始化首指针指向首元素,尾指针指向尾元素。
     *  2)如果首尾指针对应元素相加小于target,则首指针从左往右移动。
     *  3)如果首尾指针对应元素相加大于target,则尾指针从右往左移动。
     */
    public static int[] towSumII2(int[] arr,int target){
        int[] answer = new int[2];

        int head = 0;
        int tail = arr.length - 1;

        while (head < tail){
            if(arr[head] + arr[tail] > target){
                tail--;
            }if(arr[head] + arr[tail] < target){
                head++;
            }if(arr[head] + arr[tail] == target){
                answer[0] = head + 1;
                answer[1] = tail + 1;
                break;
            }
        }

        return answer;
    }

欢迎关注个人公众号,可直接扫描以下二维码或微信搜索“阿毛聊技术”进行关注。

posted @ 2020-08-12 00:47  limaodeng  阅读(85)  评论(0)    收藏  举报