leetcode 167. Two Sum II - Input array is sorted( Python )

描述

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.php

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.ios

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:less

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.
复制代码

解析

根据字典的特性,在遍历 numbers 的时候,查看是否有符合结果的两个数字,有的话直接返回索引结果,不然就将其加入字典中,时间复杂度为 O(N),空间复杂度为 O(N)。yii

解答

class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        d = {}
        for i in range(len(numbers)):
            if target - numbers[i] in d:
                return [ d[target - numbers[i]],i+1 ]
            elif numbers[i] not in d:
                d[numbers[i]] = i+1
复制代码

运行结果

Runtime: 48 ms, faster than 81.07% of Python online submissions for Two Sum II - Input array is sorted.
Memory Usage: 12.5 MB, less than 7.71% of Python online submissions for Two Sum II - Input array is sorted.
复制代码

每日格言:过去属于死神,将来属于你本身。svg

感谢支持
支付宝

支付宝

微信

微信
相关文章
相关标签/搜索