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)。
思路
利用字典数据类型的特性,减少额外的循环操作。
作者:Ken.W
出处:http://www.cnblogs.com/kenwoo
本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。
出处:http://www.cnblogs.com/kenwoo
本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。