方法总结1|豆包MarsCode AI刷题

104 阅读2分钟

近期刷题总结
353题判断数组是否单调
原思路:循环判断是否递增或者递减,问题在于没有建立标志位,无法记录之前的状态。所以在新的解题中增加了标志位,用来记录之前的规律是递增还是递减的。

def solution(nums: list) -> bool:
    # 初始化标志变量
    is_increasing = True
    is_decreasing = True
    # 遍历数组
    for i in range(1, len(nums)):
        # 检查当前元素与前一个元素的关系
        if nums[i] < nums[i - 1]:
            is_increasing = False
        if nums[i] > nums[i - 1]:
            is_decreasing = False
        # 如果两个标志变量都为False,提前返回
        if not is_increasing and not is_decreasing:
            return False
    # 返回最终结果
    return is_increasing or is_decreasin

格式化字符串 -f表达式 在 Python 中,格式化字符串是一种非常方便的方式来格式化输出。格式化字符串使用 f 前缀,并在字符串中使用大括号 {} 来插入变量或表达式。

# 保留小数点后两位
f"{num:.2f}"

259数值操作的期望计算问题
解析: 每次操作有1/2的概率选择 a1/2 的概率选择 b。操作两次后,可能的结果有:
a 被乘以 2 两次,结果为 2a + b
a 被乘以 2 一次,b 被乘以 2 一次,结果为 2a + 2b
b 被乘以 2 一次,a 被乘以 2 一次,结果为 2b + 2ab 被乘以 2 两次,结果为 a + 2b
每种结果的概率都是 1/4

def solution(a: int, b: int) -> str:
    re1=a*2*2+b
    re2=a+b*2*2
    re3=a*2+b*2
    result=re1/4+re2/4+re3/2

    return f"{result:.2f}"

486蛇形填充n阶矩阵
有题目可得,填充是按照下左上右进行的。初始位置在右上角。AI提供了一个很好的思路,我一般是两层循环,变动指针来控制,这样的方法其实非常容易越界等问题的发生。所以学习了AI的思路,提前设定填充顺序directions,然后建立一个变量direction_index用来记录此时的变换位置。

def solution(n: int) -> list:
    matrix=[[0]*n for _ in range(n)]
    x,y=0,n-1
    directions = [(1, 0), (0, -1), (-1, 0), (0, 1)]
    direction_index = 0
    # 填充数字
    for num in range(1,n*n+1):
        matrix[x][y]=num
        # 计算下一个位置
        next_x = x + directions[direction_index][0]
        next_y = y + directions[direction_index][1]
        # 检查是否需要改变方向
        if not (0 <= next_x < n and 0 <= next_y < n and matrix[next_x][next_y] == 0):
            # 改变方向
            direction_index = (direction_index + 1) % 4
            next_x = x + directions[direction_index][0]
            next_y = y + directions[direction_index][1]
        # 更新当前位置
        x,y=next_x,next_y
    
    return matrix