【问题标题】:Scattered people with heights分散的有高度的人
【发布时间】:2022-01-12 00:01:26
【问题描述】:

有一排分散的人,我们需要恢复秩序。

我们知道:

  • 他们每个人有多高
  • 在他们面前较高的人数。

此信息包含在一个集合中

Person {
    int height;
    int tallerAheadCount;
}

我尝试了多种方式对其进行排序,但没有成功。

我设法弄清楚的是,最短的人的 tallerAheadCount 应该与原始索引匹配,但这在具有排序高度的 for 循环中不起作用。

按tallerAheadCount 排序,然后按height 排序给了我们一个相对接近的答案,但tallerAheadCount 越高,它似乎越不正确。我想不出将较短的人合并到较低的tallerAheadCount 排序行的规则。

你会怎么做?

【问题讨论】:

  • 为什么这被标记为python?
  • 如果你解释一下你尝试了什么以及它是如何失败的,也许你的问题会更清楚。
  • “恢复订单”是什么意思?
  • 对不起,不够具体,问题是人们排成一列,由于紧急情况而分散。原始顺序未知,这才是真正重新分配索引的问题。标记为 python,因为该集合被格式化为 py,但是问题是问题更广泛,我删除了它。
  • 你为什么说包含int height;之类的东西被公式化为python?

标签: python algorithm sorting


【解决方案1】:

没什么可继续的,但我想这样的事情可能就是你所追求的。

这可能不是最有效的实现,并且不确定它是否涵盖所有情况(例如重复),但这是一个开始:

import random

# dummy data [(height, taller_ahead_count), ...]
original_line = [
    (10, 0), (12, 0), (3, 2), (8, 2), (9, 2), (5, 4), (1, 6), (4, 5), (2, 7)]

# "scatter" the people
scattered_line = original_line.copy()
random.shuffle(scattered_line)

# restore the original line order based on the taller_ahead_count
descending_height = sorted(scattered_line, key=lambda x: x[0], reverse=True)
restored_line = []
for height, taller_ahead_count in descending_height:
    taller_count = 0
    j = 0
    while taller_count < taller_ahead_count and j < len(restored_line):
        if restored_line[j] > height:
            taller_count += 1
        j += 1
    restored_line.insert(j, height)

# verify result
assert [height for height, __ in original_line] == restored_line

基本思路如下:

我们按照高度递减的顺序迭代人,即从最高到最低。这样,在每次迭代中,我们可以确定所有比当前人高的人都已经在restored line 中。然后我们可以计算身高较高的人的数量,以找到应该插入当前人的位置。

【讨论】:

  • 感谢@djvg 的回答,非常感谢。不,这不是我的作业,我自己正在研究排序算法,发现这个问题没有解决方案,所以我尝试解决它,但最终失败了,这就是我寻求帮助的原因。
猜你喜欢
  • 2022-01-01
  • 2022-01-27
  • 2022-11-16
  • 1970-01-01
  • 1970-01-01
  • 2020-12-05
  • 2019-01-22
  • 2014-10-21
  • 1970-01-01
相关资源
最近更新 更多