LeetCode 第1题 Two sum (easy)——python

 题目来源:

                      https://leetcode.com/problems/two-sum/description/

 题目描述:


 解决办法:

1.采用暴力算法(Brute Force),时间复杂度为O(n^2)

    其具体思路是采用循环的方式遍历整个列表,看是否能同时找到元素x和target-x
    其代码为:
    
class Solution:
    def twoSum(self, nums, target):
        for i in  range(len(nums)):
            for j in range(i,len(nums)):
                if(nums[i]==(target-nums[j])):
                    return [i,j]

2.采用HashMap的方法,时间复杂度为O(n)

    python里面的dictionary和C++中的map的功能是一样的,里面的数据是按照“键-值对”成对出现的,这样可以减少查找所用的时间。思路是:将字典中的key设定为列表中的值,value设定的是该值相对应的位置,只要满足num和target均在字典中则找到答案。
class Solution:
    def twoSum(self, nums, target):
        buff={}
        for i in range(len(nums)):
            buff[target-nums[i]]=i
        for j in range(len(nums)):
            if (nums[j] in buff.keys() and buff[nums[j]!=j]):##防止同一个元素出现两遍
                return[j,buff[nums[j]]]






          

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章