输入:votes = ["ABC","ACB","ABC","ACB","ACB"]
输出:"ACB"
解释:
A 队获得五票「排位第一」,没有其他队获得「排位第一」,所以 A 队排名第一。
B 队获得两票「排位第二」,三票「排位第三」。
C 队获得三票「排位第二」,两票「排位第三」。
由于 C 队「排位第二」的票数较多,所以 C 队排第二,B 队排第三。
示例 2:
输入:votes = ["WXYZ","XYZW"]
输出:"XWYZ"
解释:
X 队在并列僵局打破后成为排名第一的团队。X 队和 W 队的「排位第一」票数一样,但是 X 队有一票「排位第二」,而 W 没有获得「排位第二」。
classSolution { public: string rankTeams(vector<string>& votes){ int voter = votes.size(), voted = votes[0].size(); vector<vector<int>> counts(26, vector<int>(voted)); for (string& vote : votes) { for (int i = 0; i < voted; i++) { counts[vote[i] - 'A'][i]++; } } string ans = votes[0]; sort(ans.begin(), ans.end(), [&](constchar& a, constchar& b) { vector<int>& va = counts[a - 'A'], &vb = counts[b - 'A']; for (int i = 0; i < voted; i++) { if (va[i] != vb[i]) { return va[i] > vb[i]; } } return a < b; }); return ans; } };
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
''' Author: LetMeFly Date: 2024-12-29 14:58:42 LastEditors: LetMeFly.xyz LastEditTime: 2024-12-29 21:08:46 ''' """ from typing import List
class Solution: def rankTeams(self, votes: List[str]) -> str: n = len(votes[0]) counts = [[0] * n for _ in range(26)] for vote in votes: for i in range(n): counts[ord(vote[i]) - ord('A')][i] -= 1 return ''.join(sorted(votes[0], key=lambda a: (counts[ord(a) - ord('A')], a)))
funcrankTeams(votes []string)string { counts := make(map[byte][]int) for _, c := range votes[0] { counts[byte(c)] = make([]int, len(votes[0])) } for _, vote := range votes { for i, v := range vote { counts[byte(v)][i]++ } } ans := []byte(votes[0]) sort.Slice(ans, func(a, b int)bool { countA, countB := counts[ans[a]], counts[ans[b]] for i := range ans { if countA[i] != countB[i] { return countA[i] > countB[i] } } return ans[a] < ans[b] }) returnstring(ans) }