1.Two Sum——Python实现

2018-04-22  本文已影响0人  黄焖鸡叽叽

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

渣翻:
        给出一列整数,请返回这列整数其中两个数的序列,要求这两个数的和等于给定的target值。
        假设每个输入只有一组解,并且不能够两次使用同一个位置上的数。

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dict= {}
        for i in range(0,len(nums)):
            if nums[i] in dict :
                return dict[nums[i]] ,i
            else :
                dict[target - nums[i]] = i

时间复杂度为O(n)

上一篇 下一篇

猜你喜欢

热点阅读