#1. Two Sum & 167 Two Sum II - Input array is sorted

Two Sum I

https://leetcode.com/problems/two-sum/#/description

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
Subscribe to see which companies asked this question.

思路

  • 新建一个字典来保存 target - nums[i] dict{target - nums[i] : i}
  • 继续搜索,当nums[j] in dict 时,则 nums[i] + nums[j] = target
# time O(n)
# space O(n)
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dict = {}
        for i in range(len(nums)):
            if nums[i] in dict:
                return [dict[nums[i]], i]
            else:
                dict[target - nums[i]] = i

Two Sum II

https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/#/description

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. Please note that 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.
Input: numbers={2, 7, 11, 15}, target=9Output: index1=1, index2=2

你可能感兴趣的:(#1. Two Sum & 167 Two Sum II - Input array is sorted)