美文网首页
Leetcode_two sum

Leetcode_two sum

作者: 钱晓缺 | 来源:发表于2019-12-25 01:15 被阅读0次

今天开始,鄙人要刷LeetCode了。每天一题,顺带练练英语写作,嘻嘻。

About the dictionary :

 https://www.runoob.com/python3/python3-dictionary.html

First, the output expected is the index of the two numbers that add up equal to 9.

I need to think about the "enumerate" when we meet the problem with "index".

Now we think about how to traversal once.

The best way is I can find all indexes when we traversal the list.

So in this solution, we first create a dictionary to save the index of the number that is equal to target subtract the number.  So that we can get all index when we traversal once.

class Solution:

    def twoSum(self, nums: List[int], target: int) -> List[int]:

        dictionary={} ##设置一个字典

        for index,num in enumerate(nums): ##遍历nums,

            if num in dictionary: ## 如果数字在字典里面(这时候我们就得到了该数字的索引)

                return [dictionary[num],index] ## 返回字典中该数字对应的值(这个值就是target-num的索引,所以我们得到了结果)

            else:

                dictionary[target-num]=index ##把这个索引值存到target-num这一项里面,这样我们后面如果遇见了target-num,就可以把num的索引提取出来了。

相关文章

网友评论

      本文标题:Leetcode_two sum

      本文链接:https://www.haomeiwen.com/subject/fntfoctx.html