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].
解题思路
暴力:双循环算法遍历所有情况,时间复杂度为O(n^2),提交后落后99%的人。。。
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ ret = [] length = len(nums) for i in xrange(length): for j in xrange(i): if nums[i] + nums[j] == target: ret.append(j) ret.append(i) return ret
优化:空间换时间,将遍历过的数都用字典存下来,一旦碰到跟前面的数相加等于target时则返回,这下时间复杂度只有O(n)啦,提交后领先99%的人。。爽啊~~~
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ ret = [0]*2 temp = {} length = len(nums) for i in xrange(length): if (temp.has_key(target - nums[i])): ret[1] = i ret[0] = temp[target - nums[i]] return ret temp[nums[i]] = i