[本文出自天外归云的博客园]
题目:有一个数组,求他的最大(最长)连续区间(数字是连续的区间)。
我的解法,如下:
class Finder(object): ''' 判断两个相邻的数字是否连续,若连续: 1.继续向后判断 2.记录连续长度 最后返回最大连续长度 ''' def find_continuity(self,index,array,length=1): if index+1 < len(array): _curr = array[index] _next = array[index+1] if abs(_next-_curr) == 1: length += 1 length = self.find_continuity(index+1,array,length) return length ''' 将每个数字开头的索引值及最大连续区间长度存入字典 找出字典中最大的键值即最大连续区间 根据最大连续区间的索引和长度返回对应的数组切片 ''' def find_longest(self,array): continuity = dict() for i in range(len(array)): length = self.find_continuity(i,array) continuity[i] = length longest = max(continuity.items(), key=lambda x: x[1]) index,length = longest[0],longest[1] return array[index:index+length] if __name__ == '__main__': array = [1,2,3,4,5,4,2,5,3,4,7,1,5,9,10,9,8,7,6,5,4,3,4,5,6,8] finder = Finder() longest_array = finder.find_longest(array) print(longest_array)
后来我又重新写了一下这个递归过程,更简单一点:
def ret_continuous(a, ret): if len(a) == 1: return a if len(ret) == 0: ret.append(a[0]) if a[0] + 1 == a[1] or a[0] - 1 == a[1]: ret.append(a[1]) return ret_continuous(a[1:], ret) else: return ret if __name__ == '__main__': a = [1, 2, 99, 3, 4, 5, 6, 5, 4, 4, 2, 6, 3, 1, 8, 5, 3, 6] longest = [] for i in range(len(a)): ret = ret_continuous(a[i:], []) if len(ret) > len(longest): longest = ret print(longest)