這是第一題的python代碼,思路是將輸入映射成爲一個map,數組元素的值爲key,下標爲value,然後直接去map中查找target減去每一個元素之後的值,在map中找到key對應的value以及剛纔的那個索引就是返回結果。這種解法的時間複雜度只有O(N)。
突然發現python因爲有很多現成的高級數據結構,寫起算法來真方便。
#! /usr/bin/env python
"""
leetcode first, two num
"""
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: list[int]
:type target: int
:rtype: list[int]
"""
ret = []
dict = {}
for i in range(0, len(nums)):
dict[nums[i]] = i
for i in range(0, len(nums)):
other = target - nums[i]
if dict.has_key(other) and dict[other] != i:
ret.append(i)
ret.append(dict[other])
return ret
return []
if __name__ == "__main__":
s = Solution()
nums = [2, 7, 11, 15]
target = 22
ret = s.twoSum(nums, target)
for i in range(0, len(ret)):
print ret[i]