给定一个已按照非递减顺序排列的整数数组numbers,请你从数组中找出两个数满足相加之和等于目标数target

函数应该以长度为2的整数数组的形式返回这两个数的下标值。numbers的下标从 1 开始计数,所以答案数组应当满足1 <= answer[0] < answer[1] <= numbers.length

你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。

示例 1:

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

示例 2:

输入:numbers = [2,3,4], target = 6
输出:[1,3]

示例 3:

输入:numbers = [-1,0], target = -1
输出:[1,2]

提示:

  • 2 <= numbers.length <= 3 * 10^4
  • -1000 <= numbers[i] <= 1000
  • numbers按非递减顺序排列
  • -1000 <= target <= 1000
  • 仅存在一个有效答案

1.哈希
Python:

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        temp = set()
        for i in range(len(numbers)):
            diff = target - numbers[i]
            if numbers[i] not in temp:
                temp.add(diff)
            else:
                return [numbers.index(diff)+1, i+1]

Java:

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        Map<Integer, Integer> values = new HashMap<>();
        int diff;
        for(int i = 0; i < numbers.length; i++)
        {
            diff = target - numbers[i];
            if(values.containsKey(numbers[i]))
            {
                return new int[]{values.get(numbers[i])+1, i+1};
            }
            else
            {
                values.put(diff, i);
            }
        }
        return null;
    }
}

2.双指针
Python:

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        i = 0
        j = len(numbers)-1
        temp = numbers[i] + numbers[j]
        while temp != target:
            if temp < target:
                i += 1
            else:
                j -= 1
            temp = numbers[i] + numbers[j]
        return [i+1, j+1]

Java:

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        i, j = 0, len(numbers)-1
        while i < j:
            value = numbers[i] + numbers[j]
            if value > target:
                j -= 1
            elif value < target:
                i += 1
            else:
                return [i+1, j+1]
最后修改日期: 2022年1月31日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。