LeetCode

1. 两数之和

2019-03-10  本文已影响0人  cptn3m0
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        
        ret = []
        table = dict()
        # 构建字典, value->index 的映射
        for i, num in enumerate(nums):
            table[num]=i
         
        # 查找target
        for i, num in enumerate(nums):
            need_found = target - num
            if table.has_key(need_found) and table[need_found]>i:
                ret.append(i)
                ret.append(table[need_found])
        return ret
                

note

这个题目是 easy, 注意一下 python 的字典基本操作.

上一篇 下一篇

猜你喜欢

热点阅读