有一排散亂的人,我們需要恢復秩序。
我們知道:
- 他們每個人有多高
- 站在他們面前的高個子的人數。
該資訊包含在一個集合中
Person {
int height;
int tallerAheadCount;
}
我嘗試過多種方式對其進行排序,但沒有運氣。
我設法弄清楚的是,最矮的人tallerAheadCount應該與原始索引匹配,但這在具有排序高度的 for 回圈中不起作用。
排序 by tallerAheadCount,然后 byheight給了我們一個相對接近的答案,但越高tallerAheadCount似乎越不正確。我想不出將較短的人合并到較低tallerAheadCount排序行的規則。
你會怎么做?
uj5u.com熱心網友回復:
沒什么可繼續的,但我想這樣的事情可能是你所追求的。
這可能不是最有效的實作,并且不確定它是否涵蓋所有情況(例如重復),但這是一個開始:
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. 然后我們可以計算較高的人的數量,以找到應該插入當前人的位置。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/375383.html
上一篇:JavaSpark將Dataframe中的空值轉換為null
下一篇:如何垂直回圈遍歷字串陣列
