|
| 1 | +/** |
| 2 | + * 1366. Rank Teams by Votes |
| 3 | + * https://leetcode.com/problems/rank-teams-by-votes/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * In a special ranking system, each voter gives a rank from highest to lowest to all |
| 7 | + * teams participating in the competition. |
| 8 | + * |
| 9 | + * The ordering of teams is decided by who received the most position-one votes. If two |
| 10 | + * or more teams tie in the first position, we consider the second position to resolve |
| 11 | + * the conflict, if they tie again, we continue this process until the ties are resolved. |
| 12 | + * If two or more teams are still tied after considering all positions, we rank them |
| 13 | + * alphabetically based on their team letter. |
| 14 | + * |
| 15 | + * You are given an array of strings votes which is the votes of all voters in the ranking |
| 16 | + * systems. Sort all teams according to the ranking system described above. |
| 17 | + * |
| 18 | + * Return a string of all teams sorted by the ranking system. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {string[]} votes |
| 23 | + * @return {string} |
| 24 | + */ |
| 25 | +var rankTeams = function(votes) { |
| 26 | + if (votes.length === 1) { |
| 27 | + return votes[0]; |
| 28 | + } |
| 29 | + |
| 30 | + const map = new Map(votes[0].split('').map(s => { |
| 31 | + return [s, new Array(votes[0].length).fill(0)]; |
| 32 | + })); |
| 33 | + |
| 34 | + for (vote of votes) { |
| 35 | + for (let i = 0; i < vote.length; i++) { |
| 36 | + map.get(vote[i])[i]++; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + const result = votes[0].split('').sort((a, b) => { |
| 41 | + for (let i = 0; i < votes[0].length; i++) { |
| 42 | + if (map.get(a)[i] > map.get(b)[i]) return -1; |
| 43 | + if (map.get(a)[i] < map.get(b)[i]) return 1; |
| 44 | + } |
| 45 | + return a < b ? -1 : 1; |
| 46 | + }); |
| 47 | + |
| 48 | + return result.join(''); |
| 49 | +}; |
0 commit comments