Leetcode——两数之和(twoSum)、三数之和(threeSum)——Python

一、两数之和

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        #对应每个测试案例,输出两个数,小的先输出。
        # ls = []
        # if not isinstance(nums, list):
        #     return ls
        # for i, v in enumerate(nums):
        #     for v1 in nums[i:]:
        #         if (v + v1) == target:
        #             ls.append([v,v1])
        # if ls:
        #     return ls[0]
        # else:
        #     return ls
         
        keys={}
        for i in xrange(len(nums)):
            if target-nums[i] in keys:
                return [keys[target-nums[i]],i]
            if nums[i] not in keys:
                keys[nums[i]]=i

二、三数之和

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        res =[]
        lennums= len(nums)

        for i in range(lennums):
            left =i+1
            right =lennums-1
            
            if i>0 and nums[i-1]==nums[i]:
                left+=1
                continue
            
            while left0:
                    right-=1
        return res

 

你可能感兴趣的:(测试开发)