要求:考虑存取效率。
package Practice;
import java.util.ArrayList;
import java.util.HashMap;
public class RankMgr {
private ArrayList<Player> list = new ArrayList<>();
private HashMap<String, Player> map = new HashMap<>();
public static void main(String[] args) {
RankMgr rankMgr = new RankMgr();
rankMgr.addRank("1001", 22);
rankMgr.addRank("1001", 1);
rankMgr.addRank("1001", 1);
rankMgr.addRank("1001", 1);
rankMgr.addRank("1002", 10);
rankMgr.addRank("1002", 33);
rankMgr.addRank("1002", -10);
rankMgr.addRank("1002", 10);
rankMgr.addRank("1001", 10);
rankMgr.addRank("1001", 10);
rankMgr.addRank("1001", -10);
rankMgr.addRank("1001", -10);
int rank1 = rankMgr.getRank("1001");
int rank2 = rankMgr.getRank("1002");
}
public int addRank(String playerId, int value) {
if (map.containsKey(playerId)) {
int index = map.get(playerId).getRank();
if (value < 0) {
for (int i = index; i < list.size(); i++) {
if (i == list.size() - 1) {
if (value < list.get(i).value) {
break;
} else {
list.get(i).value = value;
}
}
Player playerTemp = list.get(i + 1);
if (value < playerTemp.value) {
Player player = map.get(playerId);
list.set(i + 1, player);
list.set(i, playerTemp);
player.rank = i + 1;
playerTemp.rank = i;
} else {
break;
}
}
} else {
for (int i = index; i > 0; i--) {
Player playerTemp = list.get(i - 1);
if (value > playerTemp.value) {
Player player = map.get(playerId);
list.set(i - 1, player);
list.set(i, playerTemp);
player.rank = i - 1;
playerTemp.rank = i;
} else {
break;
}
}
}
} else {
Player player = new Player(playerId, value);
map.put(playerId, player);
list.add(player);
player.rank = list.size() - 1;
if (list.size() == 1) {
list.set(0, player);
player.rank = 0;
} else {
for (int i = list.size() - 1; i > 0; i--) {
Player playerTemp = list.get(i - 1);
if (value > playerTemp.value) {
list.set(i - 1, player);
list.set(i, playerTemp);
player.rank = i - 1;
playerTemp.rank = i;
} else {
break;
}
}
}
}
return 0;
}
public int getRank(String playerId) {
if (map.containsKey(playerId)) {
System.out.println(playerId + "玩家的排名是No." + map.get(playerId).rank);
} else {
System.out.println("排行榜无" + playerId + "玩家");
}
return 0;
}
}
|