程序检查是否可以在Python中将列表拆分为连续的递增子列表
假设我们有一个称为nums的数字列表,并且以非降序排列,我们必须检查它是否可以分为任意数量的子序列,以使每个子序列的最小长度为3,并且该序列连续增加。
因此,如果输入类似于nums=[2,3,4,4,5,6,6,7],则输出将为True,因为我们可以将列表分为[2,3,4]和[4,5,6,7]。
范例(Python)
让我们看下面的实现以更好地理解-
from collections import Counter
class Solution:
def solve(self, nums):
count = Counter(nums)
starts = []
ends = []
for x in sorted(count):
if count[x] > count[x - 1]:
starts.extend([x] * (count[x] - count[x - 1]))
if count[x] > count[x + 1]:
ends.extend([x] * (count[x] - count[x + 1]))
return all(s + 2 <= e for s, e in zip(starts, ends))
ob = Solution()
nums = [2, 3, 4, 4, 5, 6, 7]
print(ob.solve(nums))输入值
[6, 7, 5, 10, 13], 2输出结果
True
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短