【LeetCode刷题日记】846

36 阅读1分钟

输入:hand = [1,2,3,4,5], groupSize = 4 输出:false 解释:Alice 手中的牌无法被重新排列成几个大小为 4 的组。

提示:

1 <= hand.length <= 104 0 <= hand[i] <= 109 1 <= groupSize <= hand.length

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/ha… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


### 题解


思路:


先排序,使用map记录数组出现的次数;  
 从小到大遍历数组,找到当前最下的数,开始寻找顺子;  
 当不满足条件时,则返回false,都可以满足条件时返回true;


**C++**



class Solution { public: bool isNStraightHand(vector& hand, int groupSize) { int n = hand.size(); if (n % groupSize != 0) { return false; } sort(hand.begin(), hand.end()); unordered_map<int, int> cnt; for (auto & num : hand) { cnt[num]++; } for (auto & x : hand) { if (!cnt.count(x)) { continue; } for (int j = 0; j < groupSize; j++) { int num = x + j; if (!cnt.count(num)) { return false; } cnt[num]--; if (cnt[num] == 0) { cnt.erase(num); } } } return true; } };


**java**



class Solution { public boolean isNStraightHand(int[] hand, int groupSize) { int n = hand.length; if (n % groupSize != 0) { return false; } Arrays.sort(hand); Map<Integer, Integer> cnt = new HashMap<Integer, Integer>(); for (int x : hand) { cnt.put(x, cnt.getOrDefault(x, 0) + 1); } for (int x : hand) { if (!cnt.containsKey(x)) { continue; } for (int j = 0; j < groupSize; j++) { int num = x + j; if (!cnt.containsKey(num)) { return false; } cnt.put(num, cnt.get(num) - 1); if (cnt.get(num) == 0) { cnt.remove(num); } } } return true; } }




---


后话,后面刷LeetCode,不能走马观花,刷完就不管了,要针对学习过的内容进行总结,对不了解的知识要迅速理解,对不熟练的知识要快速温习。


这道题设计到的知识主要是C++中STL的vector和 unordered\_map和sort()算法的了解;java中Arrays.sort、Map等的了解。


C++ STL的vector和unordered\_map可以参考下面的博客:


[【C++ STL学习笔记】C++ STL基础]( )


[【C++ STL学习笔记】C++ STL序列式容器(array,vector,deque,list)]( )


[【C++ STL学习笔记】C++ STL无序关联式容器(unordered\_map,unordered\_set)]( )


很多知识不用就容易忘记,要注意温习。


java中Arrays.sort、Map,可以参考下面的博客:


[Java数组:针对数组(Array)的各种操作]( )