【LeetCode刷题python】两数之和

题目

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

实现

class Solution(object):
    def twoSum(self,nums,target): 
 
        hasmap={
    
    }  
        #key是数字,val是下标
        for index,item in enumerate(nums):  #enumerate遍历数据对象,列出数据下标与数据
            if hasmap.has_key(target-item):
                return hasmap[target-item],index
            hasmap[item] =index

        """
        每个函数的第一个参数都是self,约定俗成指向class的实例
        list
        有序,元素类型不一定相同
        切片listname[start : end : step]
        字典
        dictname = {‘key’:‘value1’, ‘key2’:‘value2’, …, ‘keyn’:valuen}
        """
     
class Solution(object):
    def twoSum(self,nums,target): #每个函数的第一个参数都是self,约定俗成指向class的实例
        if len(nums)==0:
            return []
        for index,item in enumerate(nums):  #enumerate遍历数据对象,列出数据下标与数据
            for count in range(index+1,len(nums)):
                if item+nums[count]==target:
                    return [index,count]

总结

好久不刷算法题,哈希表都已经转不过来了,python语法也得慢慢熟悉,加油~

猜你喜欢

转载自blog.csdn.net/Magnolia_He/article/details/129308116