给定数组
[1,2,2,3,2,2,4,5,5,6,7] 作为投入。如何筛选列表以使其输出
[1,2,3,2,4,5,6,7] ?
请注意,
[2,2] -> [2],也是
[1,2,2,1] -> [1,2,1]
[1,2,3,3,2,1] -> [1,2,3,2,1]发布于 2017-10-14 08:02:05
使用itertools.groupby()
In [1]: lst = [1,2,2,3,2,2,4,5,5,6,7]
In [2]: from itertools import groupby
In [3]: [next(g) for _,g in groupby(lst)]
Out[3]: [1, 2, 3, 2, 4, 5, 6, 7]发布于 2017-10-14 08:03:50
这是两个指针问题。下面是伪代码:
start = 0
end = 1
while(end < len(arr)):
if(arr[end] != arr[start]):
arr[start + 1] = arr[end]
start += 1
end += 1
# end of while loop
# now arr[0... start] holds the result具有恒定空间的时间复杂度O(n)。
发布于 2017-10-14 08:25:34
另一种使用zip的方法:
>>> a = [1, 2, 2, 3, 2, 2, 4, 5, 5, 6, 7]
>>> [i for i,j in zip(a, a[1:] + [not a[-1]]) if i != j]
[1, 2, 3, 2, 4, 5, 6, 7]https://stackoverflow.com/questions/46742263
复制相似问题