力扣刷题python

2024-01-09 19:37:51

文章目录

1.两数之和

第一种解法

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in nums:
            j=target-i
            start_index=nums.index(i)
            next_index=start_index+1
            temp=nums[next_index:]
            if j in temp:
                return [start_index,next_index+temp.index(j)]

第二种解法

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dict={}
        for i in range(len(nums)):
            if target-nums[i] not in dict:
                dict[nums[i]]=i
            else:
                return [dict[target-nums[i]],i]

文章来源:https://blog.csdn.net/qq_45823731/article/details/135487524
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。