最も反復的な値で配列をソートするにはどうすればよいですか?
suppose I have an array [3, 3, 3, 3, 4, 4]
Expected the result as [3, 4] since 3 is most repeated and 4 is least repeated.
それを行う方法はありますか?
前もって感謝します....!
これを行う1つの方法を次に示します。
distictList
: 配列からすべての個別の値を取得し、これに格納します
countArray
: の各i
インデックスについてdistinctList
countArray[i]
、distinctList[i]
countArray
次に、同じスワップを並べ替えてdistinctList
同時に適用します。
例: [3, 3, 4, 4, 4]
個別リスト [3,4]
countArray [2,3]
降順ソート countArray [3,2] 同時にソートする distinctList [4,3] 出力: [4, 3]`
Python で簡単:
data = [3, 2, 3, 4, 2, 1, 3]
frequencies = {x:0 for x in data}
for x in data:
frequencies[x] = frequencies[x] + 1
sorted_with_repetitions = sorted(data, key=lambda x:frequencies[x],reverse=True)
sorted_without_repetitions = sorted(frequencies.keys(), key=lambda x:frequencies[x],reverse=True)
print(data)
print(sorted_with_repetitions)
print(sorted_without_repetitions)
print(frequencies)
Java にも同じアプローチ (個別の値を収集して出現回数をカウントするための連想コンテナーを使用して、カスタム比較で配列を元のデータまたは個別の項目のみで並べ替える) が適しています。