[英]Find longest ascending sequence in an array (Python)
You are given an array of numbers, say 比如,给你一组数字
nums = [2, 5, 3, 3, 4, 6]
And want to get the longest possible sequence of numbers, that are ascending, though not necessarily consequent, while maintaining their order. 并且希望获得尽可能长的数字序列,这些数字在维持其顺序的同时是提升的,但不一定是结果。
So the longest array of numbers where A n < A n+1 . 所以A n <A n + 1的最长数字数组。 In this case:
在这种情况下:
[2, 3, 4, 6]
I have done this via recursion and loops, testing every possibility. 我通过递归和循环完成了这项工作,测试了所有可能性。 This however takes way too much time for larger arrays and so my question is, whether there is a better/faster method to do this.
然而,对于较大的阵列而言,这需要花费太多时间,因此我的问题是,是否有更好/更快的方法来执行此操作。
Thanks in advance! 提前致谢!
Here's my previous code, which returned the length of the final array 这是我之前的代码,它返回了最终数组的长度
def bestLine(arr):
maximum = 0
for i in range(0, len(arr)):
if (len(arr)-i < maximum):
break
maximum = max(maximum, f(i, len(arr), arr))
return maximum
def f(start, end, arr):
best = 0
for i in range(start+1, end):
if (end-i < best):
break
if (arr[i] > arr[start]):
best = max(best, f(i, end, arr))
return 1 + best
My solution: 我的解决方案
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]
This is maybe not very "pythonic" (it resembles C or even FORTRAN code :-), but it is of O(n^2) complexity. 这可能不是非常“pythonic”(它类似于C或甚至FORTRAN代码:-),但它具有O(n ^ 2)复杂度。
If you want to get the longest sequence itself, not just its length (which may be ambiguous), the above function requires just slight modification: 如果你想获得最长的序列,而不仅仅是它的长度(可能是模糊的),上面的函数只需要稍加修改:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.