目前我面臨的情況是我有一個多維字串陣列:
var myMultiDimensionalArray = [
['foo', 'bar'],
['foo', 'baz', 'bar'],
['foe', 'bar'],
]
我想將里面的字串陣列組合/合并myMultiDimensionalArray在一起,過濾掉重復項,同時保持陣列項的順序。
因此,在處理myMultiDimensionalArray變數時,它應該導致:
var myProccessedArray = ['foo', 'foe', 'baz', 'bar']
然而,這也可能是一個可能的結果:
var myProccessedArray = ['foo', 'baz', 'foe', 'bar']
因為不清楚何時foe應該排名更高或更低baz,反之亦然。當多維陣列包含以下內容時:['foe', 'baz']那么很明顯,foe它的排名高于baz。
最好是 javascript/typescript 解決方案,但很好地解釋要尋找什么以及如何實作這樣的演算法也應該足夠了。
uj5u.com熱心網友回復:
在線性時間內,決議陣列并將每個術語映射到它出現的行。例如 'foo' => [0, 1]。
至少前面的一項只出現在它前面的行中總是正確的(假設對此有一個有效的解決方案是可能的)。
從那些只出現在其行前面的項中反復隨機抽取一個項并將其添加到您的有序串列中。
這是我們的示例地圖:
foo => [0, 1]
foe => [2]
baz => [1]
bar => [1,2,3]
Initial State: Solution = [],
Matrix:
['foo', 'bar'],
['foo', 'baz', 'bar'],
['foe', 'bar']
'foo' and 'foe' both only appear at the front of their rows. Pick one at random. E.g. 'foe'.
State: Solution = ['foe'],
Matrix:
['foo', 'bar'],
['foo', 'baz', 'bar'],
['bar']
Now the other of 'foo' and 'foe' only appears at the front of its row. Pick it.
State: Solution = ['foe', 'foo'],
Matrix:
['bar'],
['baz', 'bar'],
['bar']
Now 'baz' only appears at the front of its row. Pick it.
State: Solution = ['foe', 'foo', 'baz'],
Matrix:
['bar'],
['bar'],
['bar']
Finally, pick 'bar'. Solution = ['foe', 'foo', 'baz', 'bar']
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/377851.html
上一篇:C 中的奇怪錯誤而不停止程式
