我正在尝试使用细分树
来解决frequent valuesThis博客文章采用了类似的方法
我想将列表拆分为以下内容:
-1 -1 1 1 1 1 3 10 10 10
变为(0, 2) (2, 6) (6, 7), (7, 10)
我有一个代码:
g s = map (\x->(head x, length x)) . group . sort $ s
但它没有给出正确的输出。
是否可以使用频繁的值?
答案 0 :(得分:5)
I'd do it as
f = neighbors . prefixSums . counts
where
counts = map length . group . sort
prefixSums = scanl (+) 0
neighbors xs = zip xs (tail xs)
This starts by computing the counts
of elements, so your (arbitrary permutation of) [-1, -1, 1, 1, 1, 1, 3, 10, 10, 10]
becomes [2, 4, 1, 3]
.
Then, prefixSums
computes the sums of prefixes, and so we get [0, 2, 6, 7, 10]
for our running example.
To get the end result, we simply take the consecutive neighbors
of this list.