python基础语法及数据结构练习--day01

位1的个数

题目链接:191. 位1的个数

image-20220418130207555

这个题目传入的是一个十进制的数,我们首先需要把他转换为二进制的样子,然后再统计每一位分别是多少

而对于转化成二进制有很多方法,常用的有

  • 循环除2法
  • 与2的n次方进行与运算

这里用的是第二种方法

# -*- 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

整数的各位积和之差

题目链接:1281. 整数的各位积和之差

image-20220418130520525

这个题也比较简单,直接使用模拟统计就好了,最后不要忘掉对n进行更新,不然就会进入死循环

# -*- 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

两数之和

题目连接:1. 两数之和

image-20220418130738948

两数之和,梦想开始的地方hhh

这个题可以直接使用字典来存储整数值与其下标的对应关系,对于每一个值均检查target - num是不是在字典里出现过,如果出现过说明已经找到答案了,直接返回就可以了

由于题目已经说了一定存在一个答案,所以在循环结束之前一定能找到结果,因此就不需要异常输出了

# -*- 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

合并两个有序数组

题目链接:88. 合并两个有序数组

image-20220418130950065

这个题方法比较多,我在这里稍微提一下

  • 第一种方法:直接把数组二拼在数组一的后面,然后调用sort()函数排序即可,非常好理解

  • 第二种方法:新建一个数组,然后从头遍历nums1nums2,然后不断插入新创建的数组中,最后把新数组的每一位放到nums1中

    注意这里一定要是每一位放进去,正确写法为:nums1[:] = new_arr[:],而不能写成nums1 = new_arr,第一种写法是把nums1指向的位置的元素修改掉了,这个是题目中描述的in-place instead,第二种方法是将nums1指向了另外一个地方,但是并没有修改nums1原指向位置的值,如果还是理解不了的话可以搜一下基本类型和引用类型

  • 第三种方法:倒序遍历两个数组,找到较大者直接插入nums1的尾部即可

下面的代码是第三种方法

# -*- 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

猜你喜欢

转载自blog.csdn.net/qq_46311811/article/details/124247245