【问题标题】:Sorting Map in complexity of O(log(n))以 O(log(n)) 的复杂度对 Map 进行排序
【发布时间】:2018-06-11 19:44:04
【问题描述】:

如何按玩家id或玩家姓名对地图(复杂度为O(log(n)))进行排序??

private static final Map<Integer,Player> PLAYERS= new TreeMap<>();
       static {
           PLAYERS.put(1, new Player(1, "messi"));
           PLAYERS.put(2, new Player(7, "ronaldo"));
           PLAYERS.put(3, new Player(3, "neymar"));
           PLAYERS.put(4, new Player(4, "iniesta"));
           PLAYERS.put(5, new Player(5, "ronaldo"));
           PLAYERS.put(6, new Player(2, "pique"));
           PLAYERS.put(7, new Player(6, "suarez"));
       }

我做了这个比较器,例如:

public static Comparator<Player> PlayerNameComparator = new 
Comparator<Player>() {

public int compare(Player p1, Player p2) {

String playerName1 = p1.getName().toUpperCase();
String playerName2 = p2.getName().toUpperCase();

return playerName1.compareTo(playerName2);
}
};

但我不知道如何解决这个问题:

public static Collection getAllByName() {

Map sortedPlayersByName = new TreeMap(PLAYERS);

Collections.sort(sortedPlayersByName, Player.PlayerNameComparator);
return sortedPlayersByName.values();    
 }

【问题讨论】:

  • 阅读this
  • 您无法对地图进行排序,期间。
  • 那么我怎样才能按名称对集合进行排序并且仍然具有 O(log(n)) 的复杂性?

标签: java sorting dictionary complexity-theory


【解决方案1】:

您在示例中使用了树形图。除非您编写比较器按值对其进行排序,否则默认情况下它将按键排序。由于树图使用红黑树,您的插入时间将为 O(logN)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多