资讯专栏INFORMATION COLUMN

[LeetCode] 846. Hand of Straights

vslam / 1297人阅读

Problem

Alice has a hand of cards, given as an array of integers.

Now she wants to rearrange the cards into groups so that each group is size W, and consists of W consecutive cards.

Return true if and only if she can.

Example 1:

Input: hand = [1,2,3,6,2,3,4,7,8], W = 3
Output: true
Explanation: Alice"s hand can be rearranged as [1,2,3],[2,3,4],[6,7,8].
Example 2:

Input: hand = [1,2,3,4,5], W = 4
Output: false
Explanation: Alice"s hand can"t be rearranged into groups of 4.

Note:

1 <= hand.length <= 10000
0 <= hand[i] <= 10^9
1 <= W <= hand.length

Solution
class Solution {
    public boolean isNStraightHand(int[] hand, int W) {
        int n = hand.length;
        if (n < W || n%W != 0) return false;
        int groups = n/W;
        PriorityQueue pq = new PriorityQueue<>();
        for (int card: hand) pq.offer(card);
        
        for (int i = 0; i < groups; i++) {
            int first = pq.poll();
            for (int j = 1; j < W; j++) {
                // if (pq.remove(first+j)) continue;
                if (pq.contains(first+j)) pq.remove(first+j);
                else return false;
            }
        }
        return true;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72539.html

相关文章

  • leetcode-846-Hand of Straights

    摘要:题意分出组连续的个元素的数组思路比较简单,直接循环删除连续的数组,如此循环反复。 题意:分出n组连续的W个元素的数组 思路:比较简单,直接循环删除连续的数组,如此while循环反复。 class Solution(object): def isNStraightHand(self, hand, W): # c = collections.Counter(han...

    xiguadada 评论0 收藏0
  • leetcode31 Next Permutation

    摘要:如果当前数字代表的整数值已经是所有排列组合中的最大值,则返回当前数字组成的最小值。可是这意味着大量无用的数字的生成和比较。一个数字中的各个位上的数如何调整顺序才能获得一个最小的更大值。其次,要保证移动之后,高位以后的值为最小值。 题目要求 Implement next permutation, which rearranges numbers into the lexicographi...

    hedzr 评论0 收藏0
  • [Leetcode] Next Permutation 下一个排列

    摘要:因为增加高位会带来更大的增益。所以对于一个长为的序列,我们增加第位的前提是,前位已经达到了最大排列方法。因为是找下一个数,所以我们要找一个比小却尽可能大的数,所以找到。把换到的位置后,后三位仍然是个降序的排列。 Next Permutation Implement next permutation, which rearranges numbers into the lexicogr...

    young.li 评论0 收藏0
  • [LeetCode] 549. Binary Tree Longest Consecutive Se

    Problem Given a binary tree, you need to find the length of Longest Consecutive Path in Binary Tree. Especially, this path can be either increasing or decreasing. For example, [1,2,3,4] and [4,3,2,1] ...

    bingchen 评论0 收藏0
  • 容器最大盛水量

    摘要:容器最大盛水量给定个非负整数,,,,其中每个表示坐标,处的点。找到两条线,它们与轴一起形成一个容器,使得容器含有最多的水。 容器最大盛水量 Container With Most Water 给定n个非负整数a1,a2,...,an,其中每个表示坐标(i,ai)处的点。 绘制n条垂直线,使得线i的两个端点在(i,ai)和(i,0)处。 找到两条线,它们与x轴一起形成一个容器,使得容器...

    luckyw 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<