1366. Rank Teams by Votes
leetcode吧
全部回复
仅看楼主
level 6
milk_bread 楼主
一道中等难度。读完就有思路结果做了一天。
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.
Example 1:
Input: votes = ["ABC","ACB","ABC","ACB","ACB"]
Output: "ACB"
题目是要求 投票以后根据票数多少 进行再次排序。 比如A B两个如果选A做首选的多 那么A在前面 反之则B在前,
如果选他们为首选的人一样多。那么再比较选他们两个做第二选择的人的多少。以此类推。都相同就按字母顺序排序
这道题目看完我就有了两个想法
凡是这样的字母表的 一般都会用一个 int[26]的数组来计数。 比用dictionary还清爽
比较的规则看起来是递归了
于是动手写代码。结果犯了n次数组越界。 我的天。。。。 越界到怀疑人生。
最后虽然accept了 但是一天过去了。 我一点都不高兴。应该总结点儿什么了
2020年03月04日 06点03分 1
level 6
milk_bread 楼主
public class Solution {
public string RankTeams(string[] votes)
{
int score = votes[0].Length;
int[][] voterank = new int[score][];
for (int i = 0; i < voterank.Length; i++)
{
voterank[i] = new int[26];
}
foreach (string vote in votes)
{
for (int rank = 0; rank < vote.Length; rank++)
{
voterank[rank][vote[rank] - 'A'] += 1;
}
}
var res = new List<int>();
for(int i = 0; i < 26; i++) { res.Add(i); }
//排序
for (int loop = 0; loop < score; loop++)
{
for (int i = 25; i >= 1; i--)
{
int higher = compare2letter(res[i], res[i - 1], voterank, 0);
if (higher == res[i])
{
int temp = res[i - 1];
res[i - 1] = res[i];
res[i] = temp;
}
}
}
StringBuilder sb = new StringBuilder();
for(int i = 0; i < score; i++)
{
sb.Append((char)('A'+res[i]));
}
return sb.ToString();
}
public int compare2letter(int a,int b,int[][] voterank,int fromRow)
{
if (voterank[fromRow][a] > voterank[fromRow][b]) return a;
else if (voterank[fromRow][a] < voterank[fromRow][b]) return b;
else {
if (fromRow+1 < voterank.Length)
{
return compare2letter(a, b, voterank, fromRow+1);
}
else
{
return Math.Min(a, b);
}
}
}
}
2020年03月04日 06点03分 2
level 13
大神又开始刷了啊
2020年03月06日 05点03分 3
oh我的导师 你来啦。 我看到贴吧有人挖出我的帖子。我感慨时间过得快都一年零两个月前的题目。 但是我再接再厉发现比一年前对 BFS DFS 理解要好一些了。但是DP的依然有点懵,只能不断想背包问题套用过去。 继续刷。
2020年03月06日 08点03分
@milk_bread 可以可以,刷出厚积薄发的感觉了啊。是不是最近你们也开始work from home了,所以刷题时间多了。
2020年03月06日 21点03分
@insomnia_03 是了。 不刷题呢,就看电影去了感觉不是上班的滋味。有点良心受到鞭笞。所以刷刷看了。 这周的还有一个灯泡题我一打眼竟然有点懵,看来还要继续刷,刷到medium都能干掉然后冲锋hard
2020年03月09日 09点03分
1