这是一个简单的单遍O(n)解决方案:
s = [1,4,2,3,5,4,5,6,7,8,1,3,4,5,9,10,11,42]maxrun = -1rl = {}for x in s: run = rl[x] = rl.get(x-1, 0) + 1 print x-run+1, 'to', x if run > maxrun: maxend, maxrun = x, runprint range(maxend-maxrun+1, maxend+1)
如果您考虑范围而不是端点和游程长度的单个变量,那么逻辑可能会更加不言而喻:
rl = {}best_range = xrange(0)for x in s: run = rl[x] = rl.get(x-1, 0) + 1 r = xrange(x-run+1, x+1) if len(r) > len(best_range): best_range = rprint list(best_range)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)