LeetCode (No.167) - two numbers II - Input ordered array

Given an ordered array is sorted in ascending order according to find the two numbers such that their sum is equal to the sum of the target number.

Function should return the two index values ​​and index1 index2, which must be less than index1 index2.

Description:

  • Return values ​​of the index (index1, index2 and) is not zero.
  • You can assume that each input corresponding to only the only answer, but you can not reuse the same elements.

Example:
Input: numbers = [2, 7, 11, 15], target = 9
Output: [1,2]
Explanation: 2 and 7 is equal to the sum of the target number 9. Thus index1 = 1, index2 = 2.

Ideas: the use of the dictionary is determined whether the difference between two numbers in the dictionary, key value corresponding, value of the subscript

class Solution:
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        hashed = {}
        for i in range(len(numbers)):
            if target-numbers[i] in hashed: 
                return [hashed[target-numbers[i]], i+1]
            hashed[numbers[i]] = i+1
Published 114 original articles · won praise 55 · views 80000 +

Guess you like

Origin blog.csdn.net/zuolixiangfisher/article/details/87517428