刷题之路,道阻且长(二)| 豆包MarsCode AI刷题

112 阅读2分钟

这次还是先从一道简单的题入手,体验一下豆包的ai刷题跟别的刷题有什么不一样吧

题目:判断数组是否单调

问题描述

小S最近在研究一些数组的性质,她发现有一种非常有趣的数组被称为 单调数组。如果一个数组是单调递增或单调递减的,那么它就是单调的。

  • 当对于所有索引i <= j时,nums[i] <= nums[j],数组nums是单调递增的。
  • 当对于所有索引i <= j时,nums[i] >= nums[j],数组nums是单调递减的。

你需要编写一个程序来判断给定的数组nums是否为单调数组。如果是,返回true,否则返回false


测试样例

样例1:

输入:nums = [1, 2, 2, 3]
输出:True

样例2:

输入:nums = [6, 5, 4, 4]
输出:True

样例3:

输入:nums = [1, 3, 2, 4, 5]
输出:False

首先进行题目分析:

  1. 题目背景

    • 这是一道关于数组性质判断的编程题目。题目中引入了 “单调数组” 的概念。
  2. 关键概念

    • 单调数组

      • 单调递增:对于数组nums中的任意两个索引ij(当i <= j时),都有nums[i] <= nums[j]
      • 单调递减:对于数组nums中的任意两个索引ij(当i <= j时),都有nums[i] >= nums[j]

问题要求

-   需要编写一个程序来判断给定的数组`nums`是否为单调数组。
-   如果数组`nums`是单调递增或单调递减,那么函数应该返回`True`;否则,返回`False`

利用MarsCode AI来获得解题思路

image.png

要判断一个数组是否为单调数组,我们需要检查数组是否满足以下两个条件之一:

  1. 单调递增:对于所有索引 i <= jnums[i] <= nums[j]
  2. 单调递减:对于所有索引 i <= jnums[i] >= nums[j]

解题思路

  1. 初始化标志

    • 使用两个布尔变量 increasing 和 decreasing,初始值都为 True
  2. 遍历数组

    • 从数组的第一个元素开始,遍历到倒数第二个元素。

    • 对于每个元素 nums[i] 和它的下一个元素 nums[i+1]

      • 如果 nums[i] > nums[i+1],则数组不是单调递增的,将 increasing 设为 False
      • 如果 nums[i] < nums[i+1],则数组不是单调递减的,将 decreasing 设为 False
  3. 返回结果

    • 如果 increasing 或 decreasing 中有一个为 True,则数组是单调的,返回 True
    • 否则,返回 False

关键点

  • 通过遍历数组一次,可以在 O(n) 的时间复杂度内完成判断。

解题

def solution(nums: list) -> bool:
    increasing = decreasing = True
    for i in range(len(nums) - 1):
        if nums[i] > nums[i + 1]:
            increasing = False
        if nums[i] < nums[i + 1]:
            decreasing = False
    return increasing or decreasing

if __name__ == '__main__':
    print(solution(nums=[1, 2, 2, 3]) == True)
    print(solution(nums=[6, 5, 4, 4]) == True)
    print(solution(nums=[1, 3, 2, 4, 5]) == False)

回答正确

image.png