maxTwo 实现 Haskell
给定一个整数列表
xs
,找到两个最大值并返回 它们成对(最大的在前)。应保留最大的重复项 (包含)在输出中。请勿修改原始列表。
这是我想出的,但它并没有给出正确的答案。这是代码,第二部分是终端运行:
minInt = minBound :: Int
maxTwoHelper1 :: [Int] -> (Int, Int)
maxTwoHelper1 (x : xs) = maxTwoHelper2 minInt minInt xs
maxTwoHelper2 :: Int -> Int -> [Int] -> (Int, Int)
maxTwoHelper2 first second [] = (first, second)
maxTwoHelper2 first second (x : xs)
| x >= first = maxTwoHelper2 x second xs
| x >= second = maxTwoHelper2 first x xs
| otherwise = maxTwoHelper2 first second xs
*Main> maxTwoHelper1 [1,0,-1]
(0,-1)
Given a list of integers
xs
, find the two largest values and return
them in a pair (largest first). Largest duplicates should be preserved
(included) in the output. Do not modify the original list.
This is what I came up with but it did not quite give the correct answer. Here is the code and the second section is the terminal run:
minInt = minBound :: Int
maxTwoHelper1 :: [Int] -> (Int, Int)
maxTwoHelper1 (x : xs) = maxTwoHelper2 minInt minInt xs
maxTwoHelper2 :: Int -> Int -> [Int] -> (Int, Int)
maxTwoHelper2 first second [] = (first, second)
maxTwoHelper2 first second (x : xs)
| x >= first = maxTwoHelper2 x second xs
| x >= second = maxTwoHelper2 first x xs
| otherwise = maxTwoHelper2 first second xs
*Main> maxTwoHelper1 [1,0,-1]
(0,-1)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
maxTwoHelper1
正在删除x
,它应该考虑所有元素,因此:您的
maxTwoHelper2
还包含错误:如果x > ;=first
,x
是最大的,first
第二大,所以:Your
maxTwoHelper1
is dropping thex
, it should consider all elements, so:Your
maxTwoHelper2
also contains an error: in casex >= first
,x
is the largest, andfirst
the second largest, so:最简单的方法是使用
sortBy
:这是高效的,因为
sortBy
函数使用增量排序(它恰好是一种惰性自下而上的排序)合并排序,但也有堆排序和快速排序的增量版本可用)。只需要O(n + k * log k)
的时间即可获得对n
个元素进行排序的结果的前k
个元素。 查看这些幻灯片以获取证明。因此,获取任何固定k
(在本例中为2)的k
最大元素需要O(n)
时间。The easiest way is to use
sortBy
:This is efficient because the
sortBy
function uses an incremental sort (it happens to be a lazy bottom-up merge sort, but there are also incremental versions of heapsort and quicksort available). It only takes timeO(n + k * log k)
to get the firstk
elements of the result of sortingn
elements. See these slides for a proof. So getting thek
biggest elements for any fixedk
(in this case 2) takesO(n)
time.