leetcode classification test questions: Hash Table (1. Simple sum of two numbers)

1. When you need to quickly determine whether an element appears in a sequence , a hash table is used.
2. The summary question type targeted in this article is a simple sum of two numbers question. The difficulty of this question depends on the goal of solving it. If you need to return the index and number of the answer, it will be relatively simple; if you need If you return a tuple, triplet, etc. composed of the value of the answer, you need to consider the problem of deduplication.

1. The sum of two numbers

from typing import List
'''
1. 两数之和
给定一个整数数组nums和一个整数目标值target,请你在该数组中找出和为目标值target的那两个整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
    输入: nums = [2,7,11,15], target = 9
    输出: [0,1]
    解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
题眼:找出两个整数+返回下标——明显的key-value哈希表!!  只对应一个答案 & 数组不重复!!
思路:明确key用来表示数组元素值,value用来表示索引
'''


class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # 基本的哈希表考察
        hashTable = {
    
    }
        for i in range(len(nums)):
            if target - nums[i] in hashTable:  # 用差判断原始元素是否存在
                return [i, hashTable[target - nums[i]]]
            else:
                hashTable[nums[i]] = i  # 添加原始元素
        return []


if __name__ == "__main__":
    obj = Solution()
    while True:
        try:
            in_line = input().strip().split('=')
            nums = [int(n) for n in in_line[1].split(']')[0].split('[')[1].split(',')]
            target = int(in_line[2].strip())
            print(obj.twoSum(nums, target))
        except EOFError:
            break

454. Addition of Four Numbers II

Extension of "1. Sum of two numbers", please note that only one hash table is enough

from typing import List
'''
454. 四数相加 II
给你四个整数数组 nums1、nums2、nums3 和 nums4 ,数组长度都是 n ,请你计算有多少个元组 (i, j, k, l) 能满足:
0 <= i, j, k, l < n;  nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
示例 1:
    输入: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
    输出: 2
    解释:两个元组如下:
        1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0
        2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0
题眼:四个数组长度都是 n;  元素值和索引同时被考虑——map哈希表
思路:注意求解目标是个数:4个数组,两两分开考虑,O(N^4)降低为O(N^2)
'''


class Solution:
    def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
        # 注意求解目标是个数
        hashTable = {
    
    }
        result = 0
        # 将前两个数组按照key-value的形式进行加和存储
        for n1 in nums1:
            for n2 in nums2:
                if n1 + n2 not in hashTable:
                    hashTable[n1 + n2] = 1
                else:
                    hashTable[n1 + n2] += 1
        # 把后两个数组加和遍历,并在hashTable中查找目标元素,将满足条件的 个数 累加
        for n3 in nums3:
            for n4 in nums4:
                if 0 - (n3 + n4) in hashTable:
                    result += hashTable[0 - (n3 + n4)]
        return result


if __name__ == "__main__":
    obj = Solution()
    while True:
        try:
            in_line = input().strip().split(']')
            nums1 = [int(n) for n in in_line[0].split('[')[1].split(',')]
            nums2 = [int(n) for n in in_line[1].split('[')[1].split(',')]
            nums3 = [int(n) for n in in_line[2].split('[')[1].split(',')]
            nums4 = [int(n) for n in in_line[3].split('[')[1].split(',')]
            print(obj.fourSumCount(nums1, nums2, nums3, nums4))
        except EOFError:
            break

Guess you like

Origin blog.csdn.net/qq_39975984/article/details/132576877