Python程式:查詢汽車速度恆定的最長子列表的大小
假設我們有一個數字列表,表示汽車在等時間間隔內的位置。我們需要找到汽車以恆定速度行駛的最長子列表的大小。
因此,如果輸入類似於 positions = [0, 4, 8, 12, 6, 4, 0],則輸出將為 4,因為子列表為 [0, 4, 8, 12]。
為了解決這個問題,我們將遵循以下步驟:
- j := 1
- max_cnt := 0,current := 0
- distance := |positions[0] - positions[1]|
- 當 j < positions 的大小 時,執行以下操作:
- prev := positions[j - 1]
- 如果 distance 等於 |positions[j] - prev|,則:
- current := current + 1
- 否則:
- max_cnt := max_cnt 和 current 的最大值
- current := 1
- distance := |positions[j] - prev|
- max_cnt := max_cnt 和 current 的最大值
- j := j + 1
- 返回 max_cnt + 1
讓我們檢視以下實現以更好地理解:
示例
class Solution: def solve(self, positions): j = 1 max_cnt = 0 current = 0 distance = abs(positions[0] - positions[1]) while j < len(positions): prev = positions[j - 1] if distance == abs(positions[j] - prev): current += 1 else: max_cnt = max(max_cnt, current) current = 1 distance = abs(positions[j] - prev) max_cnt = max(max_cnt, current) j += 1 return max_cnt + 1 ob = Solution() positions = [0, 4, 8, 12, 6, 4, 0] print(ob.solve(positions))
輸入
[0, 4, 8, 12, 6, 4, 0]
輸出
4
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP