Python basic grammar and data structure exercises--day01

number of bits 1

Topic link: 191. Number of bit 1s

image-20220418130207555

In this question, a decimal number is passed in. We first need to convert it into binary, and then count the number of each digit.

There are many methods for converting into binary, commonly used are

  • Circular division by 2
  • AND operation with 2 raised to the nth power

Here is the second method

# -*- coding:utf-8
"""
作者: Jia
日期: 2022年04月18日
描述: https://leetcode-cn.com/problems/number-of-1-bits/
"""


class Solution:
    def hammingWeight(self, n: int) -> int:
        ans = sum(1 for i in range(32) if n & (1 << i))
        return ans

The difference between the sum of the products of the integers

Topic link: 1281. The difference between the sum of the products of the integers

image-20220418130520525

This question is also relatively simple, just use simulation statistics directly, and finally don't forget to update n, otherwise it will enter an infinite loop

# -*- coding:utf-8
"""
作者: Jia
日期: 2022年04月18日
描述: https://leetcode-cn.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/
"""


class Solution:
    def subtractProductAndSum(self, n: int) -> int:
        product_val = 1
        sum_val = 0
        while n > 0:
            val = n % 10
            product_val *= val
            sum_val += val
            n = n // 10
        return product_val - sum_val

sum of two numbers

Topic connection: 1. The sum of two numbers

image-20220418130738948

The sum of two numbers, where dreams begin hhh

For this question, you can directly use a dictionary to store the correspondence between integer values ​​and their subscripts. For each value, check target - numwhether it has appeared in the dictionary. If it appears, it means that the answer has been found, and you can return it directly.

Since the title has already said that there must be an answer, the result must be found before the end of the loop, so there is no need for abnormal output

# -*- coding:utf-8
"""
作者: Jia
日期: 2022年04月18日
描述: https://leetcode-cn.com/problems/two-sum/
"""
from typing import List


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

Merge two sorted arrays

Topic link: 88. Merge two sorted arrays

image-20220418130950065

There are many methods for this question, I will mention it a little here.

  • The first method: directly put the array two behind the array one, and then call the sort()function to sort, which is very easy to understand

  • The second method: create a new array, then traverse the nums1sum from nums2the beginning, and then keep inserting it into the newly created array, and finally put each bit of the new array into nums1

    Note that every bit must be put in here. The correct way to write it is: nums1[:] = new_arr[:], but it cannot be written as nums1 = new_arr, the first way of writing is to modify the element at the position pointed to by nums1, which is described in the title, and the in-place insteadsecond way is to point to nums1 Another place, but did not modify the value of the original point of nums1, if you still can't understand, you can search for basic types and reference types

  • The third method: traverse the two arrays in reverse order, find the larger one and insert it directly into the end of nums1

The code below is the third method

# -*- coding:utf-8
"""
作者: Jia
日期: 2022年04月18日
描述: https://leetcode-cn.com/problems/merge-sorted-array/
"""
from typing import List


class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        idx1 = m - 1
        idx2 = n - 1
        idx = idx1 + idx2 + 1
        while idx2 >= 0 and idx1 >= 0:
            if nums1[idx1] > nums2[idx2]:
                nums1[idx] = nums1[idx1]
                idx1 -= 1
            else:
                nums1[idx] = nums2[idx2]
                idx2 -= 1
            idx -= 1
        # 把 nums2 剩余的元素加入 nums1 中
        while idx2 >= 0:
            nums1[idx2] = nums2[idx2]
            idx2 -= 1

Guess you like

Origin blog.csdn.net/qq_46311811/article/details/124247245