python升序数_在数组中找到最长的升序(Python)

我的解决方案

def best_sequence_length(arr):

'''Find length of the longest ascending sequence in an array'''

arr_length = len(arr)

if arr_length <= 1:

return arr_length

longest = [1] # will store the lengths of the longest sequence ending on this index

best_idx_at_all = 0

for idx in range(1,arr_length):

best_len_so_far = 1

back = -1

for i in range(len(longest)+1):

if arr[i] < arr[idx] and best_len_so_far <= longest[i]:

best_len_so_far = longest[i] + 1

back = i

longest.append(longest[back]+1 if back > -1 else 1)

if longest[best_idx_at_all] < longest[idx]:

best_idx_at_all = idx

return longest[best_idx_at_all]

这可能不是非常“pythonic”(它类似于C或甚至FORTRAN代码:-),但它具有O(n ^ 2)复杂度.

如果你想获得最长的序列,而不仅仅是它的长度(可能是模糊的),上面的函数只需要稍加修改:

def best_sequence(arr):

'''Find longest ascending sequence in an array'''

arr_length = len(arr)

if arr_length <= 1:

return arr

longest = [1] # will store the length of the longest sequence ending on this index

back_link = [-1] # link to the previous element in the longest sequence or -1

best_idx_at_all = 0

for idx in range(1,arr_length):

best_len_so_far = 1

back = -1

for i in range(len(longest)+1):

if arr[i] < arr[idx] and best_len_so_far <= longest[i]:

best_len_so_far = longest[i] + 1

back = i

back_link.append(back)

longest.append(longest[back]+1 if back > -1 else 1)

if longest[best_idx_at_all] < longest[idx]:

best_idx_at_all = idx

nxt = best_idx_at_all

result = []

while nxt >= 0:

result.append(arr[nxt])

nxt = back_link[nxt]

return list(reversed(result))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值