给你一个 非递减 的正整数数组 nums 和整数 K,判断该数组是否可以被分成一个或几个 长度至少 为 K 的 不相交的递增子序列。
示例 1:
输入:nums = [1,2,2,3,3,4,4], K = 3
输出:true
解释:
该数组可以分成两个子序列 [1,2,3,4] 和 [2,3,4],
每个子序列的长度都至少是 3。
示例 2:
输入:nums = [5,6,6,7,8], K = 3
输出:false
解释:
没有办法根据条件来划分数组。
提示:
1 <= nums.length <= 10^5
1 <= K <= nums.length
1 <= nums[i] <= 10^5
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/divide-array-into-increasing-sequences 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
bool canDivideIntoSubsequences(vector<int>& nums, int K) {
unordered_map<int,int> count;
int i, maxcount = 0, n = nums.size();
for(i = 0; i < n; ++i)
{
count[nums[i]]++;
maxcount = max(maxcount, count[nums[i]]);
}
return maxcount*K <= n;
}
};
584 ms 103.7 MB
class Solution {
public:
bool canDivideIntoSubsequences(vector<int>& nums, int K) {
int pre = nums[0], cnt = 0;
for (int n : nums) {
if (n == pre)
++cnt;
else {
pre = n;
cnt = 1;
}
if (cnt * K > nums.size())
return false;
}
return true;
}
};
284 ms 69.2 MB