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

 

發佈了26 篇原創文章 · 獲贊 26 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章