力扣刷题python

文章目录

  • 1.两数之和

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]

你可能感兴趣的:(LeeCode,leetcode,python,算法)