m88明升客服m88明升客服

明陞88
明升m88手机

LeetCode_1.Two Sum

问题

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

解题

一般思路:

class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ # Time Limit Exceeded for i in range(len(nums) - 1): for j in range(i + 1, len(nums)): if nums[i] + nums[j] == target: return [i, j]

以上方法在LeetCode中运行会超时:-(

改进方式:

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

时间复杂度从O(n² )降至O(n)。

欢迎阅读本文章: 刁宏昌

m88明升备用网站

明陞88