zoukankan      html  css  js  c++  java
  • 面试题 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
    
  • 相关阅读:
    jquery的each()详细介绍【转】
    牛客-小w的a=b问题
    HDU-6707-Shuffle Card(很数据结构的一道题)
    HDU-6672-Seq
    牛客-随机数
    牛客-小阳的贝壳
    HDU-4417-Super Mario
    牛客-Corn Fields
    HDU-2665-Kth number
    线段树模板
  • 原文地址:https://www.cnblogs.com/panweiwei/p/14024808.html
Copyright © 2011-2022 走看看