[Leetcode] [Tutorial] Hashing


128. Longest continuous sequence

Given an unsorted integer array nums, find the length of the longest sequence of consecutive numbers (the sequence elements are not required to be consecutive in the original array).

Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest continuous sequence of numbers is [1, 2, 3, 4]. Its length is 4.

Solution

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        num_set = set(nums)  # 使用set更合适
        longest_streak = 0

        for num in num_set:
            if num - 1 not in num_set:
                streak = 1
                while num + 1 in num_set:
                    streak += 1
                    num += 1
                longest_streak = max(longest_streak, streak)

        return longest_streak

1. The sum of two numbers

Given an integer array nums and an integer target value target, please find the two integers in the array whose sum is the target value target and return their array subscripts.

You can assume that each input will correspond to only one answer. However, the same element in the array cannot appear repeatedly in the answer.
You can return answers in any order.

Example:
Input: nums = [3,2,4], target = 6
Output: [1,2]

Solution

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dic = {
    
    }
        for i, num in enumerate(nums):
            if target - num in dic:
                return [dic[target - num], i]
            dic[num] = i
        return []

49. Alphabet anagram grouping

You are given an array of strings, and you are asked to combine the anagrams together. The list of results can be returned in any order.

An anagram is a new word obtained by rearranging all the letters of the source word.

Example:
Input: strs = ["eat", "tea", "tan", "ate", "nat", "bat"] Output: [["bat"],["nat","tan"]
, ["ate","eat","tea"]]

Solution

To ensure that each anagram has the same tuple representation, we can ensure that each string is sorted alphabetically, and then use this sorted string as the key of the hash map.

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        anagrams = defaultdict(list)
        for s in strs:
            # 对每个字符串的字符进行排序,然后将其作为键
            sorted_s = "".join(sorted(s))
            # 将原始字符串添加到对应的列表中
            anagrams[sorted_s].append(s)
        # 将字典中的所有值(即每个列表)添加到一个结果列表中
        return list(anagrams.values())

Python's dictionaries do not allow mutable objects (such as lists) as keys. You can convert the sorted list to a string and then use this string as a dictionary key. You can do this by using the join method.

If you try to access a key that does not exist in the dictionary, Python will raise a KeyError exception. You can use defaultdict to avoid this problem, or check if the key exists before adding the element.

In addition, it should be noted that the values() method of the dictionary in Python returns a dict_values ​​object, which is not a list, but an iterator. In order to meet the return type requirements, it needs to be converted to a list. You can achieve this by using the list() function.

If you wish to use a Counter object, if you use tuple(Counter(char)) directly, what you actually get is a tuple containing the keys of the dictionary. This can cause a problem, for example for the two strings "boo" and "bob" you will get the same keys (b, o) even though they are not anagrams. When converting to tuples, you should ensure that the keys are consistent and not rely on the order in which the letters appear.

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        res = {
    
    }
        for char in strs:
            key = tuple(sorted((ch, freq) for ch, freq in Counter(char).items()))
            if key not in res:
                res[key] = [char]
            else:
                res[key].append(char)
        return list(res.values())

Guess you like

Origin blog.csdn.net/weixin_45427144/article/details/131257678