1366. Rank Teams by Votes (M)

Rank Teams by Votes (M)

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"
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.

Example 2:

Input: votes = ["WXYZ","XYZW"]
Output: "XWYZ"
Explanation: X is the winner due to tie-breaking rule. X has same votes as W for the first position but X has one vote as second position while W doesn't have any votes as second position. 

Example 3:

Input: votes = ["ZMNAGUEDSJYLBOPHRQICWFXTVK"]
Output: "ZMNAGUEDSJYLBOPHRQICWFXTVK"
Explanation: Only one voter so his votes are used for the ranking.

Example 4:

Input: votes = ["BCA","CAB","CBA","ABC","ACB","BAC"]
Output: "ABC"
Explanation: 
Team A was ranked first by 2 voters, second by 2 voters and third by 2 voters.
Team B was ranked first by 2 voters, second by 2 voters and third by 2 voters.
Team C was ranked first by 2 voters, second by 2 voters and third by 2 voters.
There is a tie and we rank teams ascending by their IDs.

Example 5:

Input: votes = ["M","M","M","M"]
Output: "M"
Explanation: Only team M in the competition so it has the first rank.

Constraints:

  • 1 <= votes.length <= 1000
  • 1 <= votes[i].length <= 26
  • votes[i].length == votes[j].length for 0 <= i, j < votes.length.
  • votes[i][j] is an English upper-case letter.
  • All characters of votes[i] are unique.
  • All the characters that occur in votes[0] also occur in votes[j] where 1 <= j < votes.length.

题意

给定一个字符串数组,其中每个字符串为相同大写英文字母集的不同组合,越靠前的字符权重越高。要求将该大写字母集按照总出现权重之和进行排序。

思路

建立对应的hash数组,统计每个字母在不同位置上出现的次数,接下来有两种处理方法:

  1. 将出现的次数转化为一个字符串进行比较。例如:[“ABC”,“ACB”,“ABC”,“ACB”,“ACB”], 'A’在3个位置上的出现次数为[5, 0, 0],则将该信息转化为"000500000000A",最后对得到的所有类似字符串按照规则排序即可。
  2. 不转化为数组,直接利用HashMap进行排序。

代码实现 - 字符串排序

class Solution {
    public String rankTeams(String[] votes) {
        int len = votes[0].length();
        int[][] count = new int[26][len];
        boolean[] exist = new boolean[26];

        // 统计出现次数
        for (int i = 0; i < votes.length; i++) {
            String vote = votes[i];
            for (int j = 0; j < len; j++) {
                char c = vote.charAt(j);
                exist[c - 'A'] = true;
                count[c - 'A'][j]++;
            }
        }

        // 转化为字符串
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 26; i++) {
            if (exist[i]) {
                String s = "";
                for (int j = 0; j < len; j++) {
                    String temp = "" + count[i][j];
                    while (temp.length() != 4) {
                        temp = "0" + temp;
                    }
                    s += temp;
                }
                s += (char) (i + 'A');
                list.add(s);
            }
        }

        // 按要求进行排序
        Collections.sort(list, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                if (s1.substring(0, 4 * len).compareTo(s2.substring(0, 4 * len)) > 0) {
                    return -1;
                } else if (s1.substring(0, 4 * len).compareTo(s2.substring(0, 4 * len)) < 0) {
                    return 1;
                } else {
                    return s1.charAt(4 * len) - s2.charAt(4 * len);
                }
            }
        });

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            sb.append(list.get(i).charAt(4 * len));
        }
        
        return sb.toString();
    }
}

代码实现 - 直接排序

class Solution {
    public String rankTeams(String[] votes) {
        int len = votes[0].length();
        Map<Character, int[]> hash = new HashMap<>();

        // 统计出现次数
        for (int i = 0; i < votes.length; i++) {
            String vote = votes[i];
            for (int j = 0; j < len; j++) {
                char c = vote.charAt(j);
                if (!hash.containsKey(c)) {
                    hash.put(c, new int[len]);
                }
                hash.get(c)[j]++;
            }
        }

        // 按要求排序
        List<Character> list = new ArrayList<>();
        for (char c : hash.keySet()) {
            list.add(c);
        }
        Collections.sort(list, new Comparator<Character>() {
            @Override
            public int compare(Character c1, Character c2) {
                for (int i = 0; i < len; i++) {
                    if (hash.get(c1)[i] != hash.get(c2)[i]) {
                        return hash.get(c2)[i] - hash.get(c1)[i];
                    }
                }
                return c1 - c2;
            }
        });

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            sb.append(list.get(i));
        }

        return sb.toString();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package self.cases.teams.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import self.cases.teams.utils.DateUtils; import self.cases.teams.utils.IDUtils; import self.cases.teams.msg.R; import self.cases.teams.msg.PageData; import self.cases.teams.entity.Users; import self.cases.teams.service.UsersService; /** * 系统请求响应控制器 * 系统用户 */ @Controller @RequestMapping("/users") public class UsersController extends BaseController { protected static final Logger Log = LoggerFactory.getLogger(UsersController.class); @Autowired private UsersService usersService; @RequestMapping("") public String index() { return "pages/Users"; } @GetMapping("/info") @ResponseBody public R getInfo(String id) { Log.info("查找指定系统用户,ID:{}", id); Users users = usersService.getOne(id); return R.successData(users); } @GetMapping("/page") @ResponseBody public R getPageInfos(Long pageIndex, Long pageSize, Users users) { Log.info("分页查找系统用户,当前页码:{}," + "每页数据量:{}, 模糊查询,附加参数:{}", pageIndex, pageSize, users); PageData page = usersService.getPageInfo(pageIndex, pageSize, users); return R.successData(page); } @PostMapping("/add") @ResponseBody public R addInfo(Users users) { if(usersService.getUserByUserName(users.getUserName()) == null){ users.setId(IDUtils.makeIDByCurrent()); users.setCreateTime(DateUtils.getNowDate()); Log.info("添加系统用户,传入参数:{}", users); users
最新发布
05-30
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值