【问题标题】:minimum difference between numbers数字之间的最小差异
【发布时间】:2013-04-03 11:15:28
【问题描述】:

我们有 K 组不同的数字。我们必须从每组中选择一个数字,这样高数和低数之间的差就是最小值

有什么想法吗?

【问题讨论】:

  • 每组有多少个元素? K 可以有多大?
  • @simplecoder:显然不是;只需考虑两个集合 {1,2,3} 和 {-3,-2,-1}
  • 请表现出你自己的一些努力。例如,首先告诉我们您考虑了哪些方法以及为什么它们不起作用。这样我们就可以帮助您,并且您实际上能够学到一些东西。
  • stackoverflow.com/q/12401915/469210 是排序列表而不是集合的相同问题。您可以通过对集合的内容进行排序以形成排序列表来转换您的问题,从而使用该解决方案。
  • @simplecoder K 是集合的数量,而不是集合的下限。没有对集合中的数字做出任何假设。显然,取每组中的最小值是从不可靠的方法,即使数字有界限。 (另一个简单的例子:集合 {0,1,2,3} 和 {2,3,4} -> 从这两个集合中取“2”,答案是 0)

标签: algorithm sorting minimum


【解决方案1】:

类似这样的东西(用 Haskell 编写)?

import Data.List (minimum, maximum, minimumBy)

minDiff (x:xs) = comb (head x) (diff $ matches (head x)) x where
  lenxs = length xs
  diff m = maximum m - minimum m
  matches y = minimumBy (\a b -> compare (diff a) (diff b)) $ p [] 0 where
    md = map (minimumBy (\a b -> compare (abs (a - y)) (abs (b - y)))) xs
    mds = [m | m <- foldl (\b a -> filter (\z -> abs (z - y) == abs (y - md!!a)) (xs!!a) : b) [] [0..lenxs - 1]]
    p result index
      | index == lenxs = [y:result]
      | otherwise      = do
          p' <- mds!!index
          p (p':result) (index + 1)
  comb result difference []     = matches result
  comb result difference (z:zs) =
    let diff' = diff (matches z)
    in if diff' < difference
          then comb z diff' zs
          else comb result difference zs


OUTPUT:
*Main> minDiff [[1,3,5,9,10],[2,4,6,8],[7,11,12,13]]
[5,6,7]

【讨论】:

  • 对于不了解 Haskell 的人来说可能无法阅读(或者至少难以阅读)。在给出算法答案时,尽量包含算法描述、cmets 和/或伪代码。
猜你喜欢
  • 2020-11-05
  • 2019-10-06
  • 1970-01-01
  • 2020-11-09
  • 1970-01-01
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多