算法

1.双指针法:

  例题:

  来源:力扣(LeetCode)
  链接:https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted

  给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。

函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。

说明:

  返回的下标值(index1 和 index2)不是从零开始的。
  你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
  示例:

  输入: numbers = [2, 7, 11, 15], target = 9
  输出: [1,2]
  解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。

自己的解法:

 public int[] twoSum(int[] numbers, int target) {
        int[] res = new int[2];
        for(int i = 0;i<numbers.length-1;i++){
            for(int j = i+1;j<numbers.length;j++){
                if(numbers[i]+numbers[j]==target){
                res[0]=i+1;
                res[1]=j+1;
                return res;
           }
            }
            
        }
        return res;
        
    }

这属于硬编码,时间复杂度O(n2

官方解法:

利用双指针法和数组为有序的特点:

方法 1:双指针
算法

我们可以使用 两数之和 的解法在 O(n^2)O(n
2
) 时间 O(1)O(1) 空间暴力解决,也可以用哈希表在 O(n)O(n) 时间和 O(n)O(n) 空间内解决。然而,这两种方法都没有用到输入数组已经排序的性质,我们可以做得更好。

我们使用两个指针,初始分别位于第一个元素和最后一个元素位置,比较这两个元素之和与目标值的大小。如果和等于目标值,我们发现了这个唯一解。如果比目标值小,我们将较小元素指针增加一。如果比目标值大,我们将较大指针减小一。移动指针后重复上述比较知道找到答案。

 public int[] twoSum(int[] numbers, int target) {
        int[] arr=new int[2];
        int low = 0;
        int high = numbers.length - 1;
        while (low < high) {
            int sum = numbers[low] + numbers[high];
            if (sum == target){
                arr[0]=low+1;
                arr[1]=high+1;
                return arr;
            }else if (sum < target){
                ++low;
            }
            else{
                --high;
            }
        }
        return arr;        
    }
原文地址:https://www.cnblogs.com/chcha1/p/11545785.html