1. 两数之和

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 的字典基本操作.

    原文作者:cptn3m0
    原文地址: https://www.jianshu.com/p/307c5c8f65b4
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞