示例:我有陣列 [9,0,1,2,3,6,4,5,0,9,7,8,9] 并且它應該回傳最大連續子序列,所以答案應該是(如果數字是 9,下一個是 0 就好了)9,0,1,2,3,但我的代碼回傳 0,1,2,3
uj5u.com熱心網友回復:
我們可以使用差值必須是 9 或 1 的事實:
arr = np.array([9,0,1,2,3,6,4,5,0,9,7,8,9])
out = max(np.split(arr, np.where(~np.isin(np.diff(arr),[-9,1]))[0] 1), key=len)
輸出:
array([9, 0, 1, 2, 3])
uj5u.com熱心網友回復:
從每個元素開始,回圈比較相鄰元素,直到得到一對不連續的元素。
而不是將所有連續的子串列保存在另一個串列中,只需將子串列保存在一個變數中。當你得到另一個子串列時,檢查它是否更長并替換它。
def constructPrintLIS(arr: list, n: int):
longest_seq = []
for i in range(n-1):
for j in range(i, n-1):
if not (arr[j] == arr[j 1]-1 or (arr[j] == 9 and arr[j 1] == 0)):
break
else:
# if we reach the end, need to update j
j = n
if j - i > len(longest_seq):
longest_seq = arr[i:j 1]
if n - i <= len(longest_seq):
# there can't be any longer sequences, so stop
break
printLIS(longest_seq)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/385276.html
標籤:python-2.7
