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 left<right:
                sumthree = nums[i]+nums[left]+nums[right]
                if sumthree==0:
                    res_col = [nums[i],nums[left],nums[right]]
                    res.append(res_col)
                    left+=1
                    right-=1
                    
                    while nums[left]==nums[left-1] and left<right:
                        left+=1
                    while nums[right]==nums[right+1] and left<right:
                        right-=1
                              
                if sumthree<0:
                    left+=1
                if sumthree>0:
                    right-=1
        return res

 

展开阅读全文

没有更多推荐了,返回首页