【数组】B062_LC_通过投票对团队排名(排序技巧)

一、Problem

In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the competition.

The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter.

Given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above.

Return a string of all teams sorted by the ranking system.

Input: votes = ["ABC","ACB","ABC","ACB","ACB"]
Output: "ACB"
Explanation: Team A was ranked first place by 5 voters. No other team was voted as first place so team A is the first team.
Team B was ranked second by 2 voters and was ranked third by 3 voters.
Team C was ranked second by 3 voters and was ranked third by 2 voters.
As most of the voters ranked C second, team C is the second team and team B is the third.

二、Solution

方法一:排序

  • 统计每只队伍的排名占据情况到 int[][] mp 中
  • 先按照每种排名获得投票的票数降序排列,如果票数相同则按字典序排列。
class Solution {
    public String rankTeams(String[] vs) {
        int N = vs[0].length(), mp[][] = new int[26][N];
        for (String v : vs) {
            for (int i = 0; i < v.length(); i++)
                mp[v.charAt(i)-'A'][i]++;
        }
        Character[] res = new Character[N];
        for (int i = 0; i < vs[0].length(); i++) 
            res[i] = vs[0].charAt(i);

        Arrays.sort(res, (c1, c2) -> {
            for (int i = 0; i < N; i++) {
                if (mp[c1-'A'][i] != mp[c2-'A'][i])
                    return mp[c2-'A'][i] - mp[c1-'A'][i];
            }
            return c1 - c2;
        });
        char[] ans = new char[N];
        for (int i = 0; i < N; i++) ans[i] = res[i];
        return String.valueOf(ans);
    }
}

复杂度分析

  • 时间复杂度:O(n2)O(n^2)
  • 空间复杂度:O(n)O(n)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章