Re: [闲聊] 每日leetcode

楼主: SecondRun (雨夜琴声)   2024-06-06 09:50:41
846. Hand of Straights
给定一整数阵列和分组大小
回传可否把数字分组,每一组的数字要连续
Example 1:
Input: hand = [1,2,3,6,2,3,4,7,8], groupSize = 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], groupSize = 4
Output: false
Explanation: Alice's hand can not be rearranged into groups of 4.
思路:
先把数字出现次数记起来
找出一组里最小的数字
把后面几组都扣掉同样次数,扣失败就return false
C# code:
public class Solution
{
public bool IsNStraightHand(int[] hand, int groupSize)
{
if (hand.Length % groupSize != 0) return false;
var dict = new Dictionary<int, int>();
foreach (int key in hand)
{
if (dict.ContainsKey(key)) dict[key]++;
else dict[key] = 1;
}
var keys = dict.Keys.ToList();
keys.Sort();
foreach (int start in keys)
{
if (dict.TryGetValue(start, out int count) == false) continue;
for (int i = 0; i < groupSize; i++)
{
int key = start + i;
if (dict.ContainsKey(key) == false) return false;
dict[key] -= count;
if (dict[key] < 0) return false;
if (dict[key] == 0)
{
dict.Remove(key);
}
}
}
return true;
}
}
作者: JIWP (JIWP)   2024-06-06 09:55:00
大师
作者: DJYOSHITAKA (Evans)   2024-06-06 10:15:00
别卷了
作者: deatheo (逆十字)   2024-06-06 11:12:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com