846. Hand of Straights - LeetCode

Question

846. Hand of Straights

Solution

题目大意:打牌,判断牌是否能全部按顺子出

思路:构造一个list,存储1,2,3,4,5,6,7,8并排序,构造一个map存储每个数对应出现的次数

Java实现:

public boolean isNStraightHand(int[] hand, int W) {
    List<Integer> nums = new ArrayList<>();
    Map<Integer, Integer> map = new HashMap<>(); // num, count
    for (int tmp : hand) {
        Integer count = map.get(tmp);
        if (count == null) {
            count = 0;
            nums.add(tmp);
        }
        map.put(tmp, count+1);
    }

    Collections.sort(nums); // sort

    int i=0;
    while (i < nums.size()) {
        int tmp = nums.get(i);
        int offset = 0;
        while (offset < W) {
            Integer count = map.get(tmp + offset);
            if (count == null || count < 1) return false;
            map.put(tmp + offset, count-1);
            offset++;
        }
        while (i < nums.size() && map.get(nums.get(i)) == 0) i++;
    }

    return true;
}
posted @ 2018-08-08 17:32  okokabcd  阅读(388)  评论(0编辑  收藏  举报