用 Python 编写程序查找最短子列表,排序后整个列表将按排序顺序排列
pythonserver side programmingprogramming更新于 2026/1/6 22:36:17
假设我们有一个名为 nums 的数字列表,我们必须找到 num 中最短子列表的长度,如果子列表已排序,则整个数组 nums 将按升序排序。
因此,如果输入为 nums = [1,2,5,4,9,10],则输出将为 2,因为对子列表 [4, 3] 进行排序将得到 [0, 1, 3, 4, 8, 9]
要解决这个问题,我们将遵循以下步骤 −
- f:= -1, l:= -1
- lst:= 对列表 nums 进行排序
- 对于范围从 0 到 nums 大小的 i,执行
- 如果 nums[i] 与 lst[i] 不同,则
- 如果 f 与 -1 相同,则
- f := i
- 否则,
- l := i
- 如果 f 与 -1 相同,则
- 如果 nums[i] 与 lst[i] 不同,则
- 如果 l 与 -1 相同且 f 与 -1 相同,则
- 返回 0
- 返回 l - f + 1
让我们看看下面的实现以便更好地理解 −
示例
class Solution: def solve(self, nums): f=-1 l=-1 lst=sorted(nums) for i in range(len(nums)): if nums[i]!=lst[i]: if f == -1: f=i else: l=i if l == -1 and f == -1: return 0 return l-f+1 ob = Solution() print(ob.solve([1,2,5,4,9,10]))
输入
[1,2,5,4,9,10]
输出
2
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

