复杂度为 O(log(n)) 的排序映射



如何按玩家的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();    
}

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

最新更新