位1的个数
题目链接:191. 位1的个数
这个题目传入的是一个十进制的数,我们首先需要把他转换为二进制的样子,然后再统计每一位分别是多少
而对于转化成二进制有很多方法,常用的有
- 循环除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. 整数的各位积和之差
这个题也比较简单,直接使用模拟统计就好了,最后不要忘掉对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. 两数之和
两数之和,梦想开始的地方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. 合并两个有序数组
这个题方法比较多,我在这里稍微提一下
第一种方法:直接把数组二拼在数组一的后面,然后调用
sort()
函数排序即可,非常好理解第二种方法:新建一个数组,然后从头遍历
nums1
和nums2
,然后不断插入新创建的数组中,最后把新数组的每一位放到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