[力扣] 算法 1296 (C#)

1296. 划分数组为连续数字的集合

public class Solution
{
    public bool IsPossibleDivide(int[] nums, int k)
    {
        if (k > 1)
        {
            var map = new SortedDictionary<int, int>();
            foreach (var num in nums)
                if (map.ContainsKey(num))
                    map[num]++;
                else
                    map[num] = 1;
            while(map.Count > 0)
            {
                var (key,value) = map.First();
                for(var i = 0; i < k; i++)
                {
                    if (!map.ContainsKey(key + i) || (map[key + i] -= value) < 0)
                        return false;
                    if (map[key + i] == 0)
                        map.Remove(key + i);
                }
            }
        }
        return true;
    }
}

发表评论