1. 程式人生 > 實用技巧 >面試題 16.24. 數對和

面試題 16.24. 數對和



程式碼一:雙指標

class Solution(object):
    # 雙指標
    def pairSums(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        if not nums:
            return []
        nums.sort()
        res = []
        i, j = 0, len(nums) - 1
        while i < j:
            temp = nums[i] + nums[j]
            if temp > target:
                j -= 1
            elif temp < target:
                i += 1
            else:
                res.append([nums[i], nums[j]])
                i += 1
                j -= 1
        return res

程式碼二:雜湊表

class Solution(object):
    def pairSums(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        nums.sort()
        mydict = {}
        for i, item in enumerate(nums):
            if item in mydict.keys():
                mydict[item] += 1
            else:
                mydict[item] = 1
        print(mydict)
        res = []
        for item in nums:

            if target - item in mydict.keys() and mydict[item] > 0:
                mydict[item] -= 1
                if mydict[target - item] > 0:
                    res.append([item, target - item])
                    mydict[target - item] -= 1
        return res