Python force button brushing question 05-effective letter anagram & intersection of two arrays & happy number & sum of two numbers

242. Effective anagrams

Question link: https://leetcode.cn/problems/valid-anagram/

Title description: Given two strings s and t, write a function to determine whether t is an anagram of s.

Note: If each character in s and t appears the same number of times, then s and t are said to be anagrams of each other.

case:

输入: s = "anagram", t = "nagaram"
输出: true

accomplish:

Method 1: Use the Counter() of the collections module to count each character

#方法一:
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        return Counter(s) == Counter(t)
        # Counter({'a': 3, 'n': 1, 'g': 1, 'r': 1, 'm': 1})

Method Two:

①: Because the characters given in the title are lowercase, English lowercase a~z has a total of 26 characters, so create an empty list with all 0s and a length of 26 to count the number of characters, then the index subscript value of az is 0- 25. The purpose of this is to make each character in s or t correspond to an empty list

②: So how to count the number of characters? Here first use s[i] - "a" + 1 to map each character to the position corresponding to the index of the empty list. Here, "a" is subtracted because the index value of a is 0, and any conversion to ASCII The value of the character minus a is in the range of 0~26, which is why an empty list with a length of 26 is created, assuming that the character "n" appears once

③: t[i] - "a" -1, if the same character appears, then it will count the number of times the character appeared before s -1 is equal to 0, then the number of characters "n" here will become 0, Achieved the purpose of comparing the number of occurrences of two characters

You can use the following picture to help understand:

Please add a picture description

# 方法二:
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        record = [0] * 26
        for i in range(len(s)):
            record[ord(s[i]) - ord("a")] += 1
        # print(record)
        for i in range(len(t)):
            record[ord(t[i]) - ord("a")] -= 1
        # print(record)
        # 判断是否有不一致的字符出现   
        for i in range(26):
            if record[i] != 0:
                return False
        return True

349. Intersection of Two Arrays

Link to the topic: https://leetcode.cn/problems/intersection-of-two-arrays/

Title Description: Given two arrays nums1and nums2, return their intersection . Each element in the output must be unique . We can ignore the order of the output results .

case:

输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]

accomplish:

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        # 使用set()先求集合交集,在变为list类型
        return list(set(nums1) & set(nums2))

202. Happy Numbers

Link to the topic: https://leetcode.cn/problems/happy-number/

Title description: Write an algorithm to judge whether a number n is a happy number.

"Happy Number" is defined as:

For a positive integer, each time the number is replaced by the sum of the squares of the digits in each position.

  • Then repeat this process until the number becomes 1, or it may be an infinite loop but it never becomes less than 1.
  • If the result of this process is 1, then the number is a happy number.
  • Returns true if n is a happy number; otherwise, returns false.

case:

输入:n = 19
输出:true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

Ideas:

The title says that there will be an infinite loop, so that means that during the summation process, the sum will appear repeatedly, which is very important for solving the problem!

When we encounter the need to quickly determine whether an element appears in the set, we must consider hashing.

So this topic uses the hash method to judge whether the sum is repeated. If it is repeated, it will return false, otherwise it will find the sum until it is 1.

You can use set() to determine whether the sum is repeated.

accomplish:

class Solution:
    def isHappy(self, n: int) -> bool:

        def calculate_happy(num):
            sum_num = 0
            # 从个位数开始取值,平方求和
            while num:
                sum_num += (num % 10) **2
                num = num // 10
            return sum_num

        # recor记录中间结果,用来存放平方和不为1的值
        record = set()
        while True:
            n = calculate_happy(n)
            if n == 1:
                return True
            # 如果中间结果重复出现,说明陷入死循环
            if n in record:
                return False
            else:
                record.add(n)

1. The sum of two numbers

Link to the topic: https://leetcode.cn/problems/two-sum/

Title description: Given an integer array nums and an integer target value target, please find the two integers whose sum is the target value target in the array, and return their array subscripts. You can assume that there is only one answer for each input. However, the same element in the array cannot appear repeatedly in the answer. You can return answers in any order.

case:

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

accomplish:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        records = dict()
        # 用枚举法获取索引和值
        for idx,val in enumerate(nums):
            # print(idx,val)
            if target - val not in records:
                records[val] = idx
            else:
                # 如果存在就返回字典记录索引和当前索引
                return [records[target - val],idx]

think:

<1> Why do you think of using hashing for this question?

When we need to query whether an element has appeared, or whether an element is in a collection, we must first think of hashing.

For this question, I need a collection to store the elements we have traversed, and then ask this collection when traversing the array, whether an element has been traversed, that is, whether it appears in this collection. Then we should think of using hashing.

Guess you like

Origin blog.csdn.net/modi88/article/details/127632395