用 Python 检查数组是否已排序和旋转的程序
pythonserver side programmingprogramming更新于 2025/5/3 3:24:17
假设我们有一个名为 nums 的数组,我们必须检查该数组最初是否按非递减顺序排序,然后旋转了一些位置(可能是零)。数组中也可能存在重复项。
因此,如果输入为 nums = [12,15,2,5,6,9],则输出将为 True,因为它向右旋转了两个位置
为了解决这个问题,我们将遵循以下步骤 −
j := 0
while j < nums 的大小 - 1 且 nums[j] <= nums[j + 1],则执行
j := j + 1
res := (从索引 j + 1 到 nums 末尾的 nums 子数组) 连接 (从索引 0 到 nums 的 j 的 nums 子数组)
对于 i,范围从 0 到 res 的大小 - 1,则执行
如果 res[i] > res[i + 1],则
返回 False
返回 True
示例 (Python)
让我们看看下面的实现以便更好地理解 −
def solve(nums): j = 0 while (j < len(nums) - 1 and nums[j] <= nums[j + 1]): j += 1 res = nums[j + 1 : len(nums)] + nums[0:j + 1] for i in range(len(res) - 1): if res[i] > res[i + 1]: return False return True nums = [12,15,2,5,6,9] print(solve(nums))
输入
[12,15,2,5,6,9]
输出
True
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

