Python程式:檢查列表是否可以拆分為連續遞增的子列表


假設我們有一個名為nums的數字列表,該列表按非遞減順序排序,我們必須檢查它是否可以拆分為任意數量的子序列,使得每個子序列至少有3個長度且連續遞增。

因此,如果輸入類似於nums = [2, 3, 4, 4, 5, 6, 7],則輸出將為True,因為我們可以將列表拆分為[2, 3, 4]和[4, 5, 6, 7]。

為了解決這個問題,我們將遵循以下步驟:

  • counts := 一個包含nums的元素及其計數的對映
  • starts := 一個新的列表
  • ends := 一個新的列表
  • 對於count中專案的每個x(按排序順序),執行:
    • 如果count[x] > count[x - 1],則
      • l := 大小為(count[x] - count[x - 1])的列表,並用x填充
      • 將l插入starts
    • 如果count[x] > count[x + 1],則
      • l := 大小為(count[x] - count[x + 1])的列表,並用x填充
      • 將l插入starts
  • 當所有(start, end)對滿足(start + 2 <= end)時返回true,否則返回false

示例(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

更新於:2020年12月12日

311 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告