LeetCode 1121. 将数组分成几个递增序列
发布日期:2021-07-01 03:30:05 浏览次数:2 分类:技术文章

本文共 1370 字,大约阅读时间需要 4 分钟。

文章目录

1. 题目

给你一个 非递减 的正整数数组 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^51 <= K <= nums.length1 <= nums[i] <= 10^5

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/divide-array-into-increasing-sequences
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

  • 题目要求每个子序列严格递增,所以每个子序列里没有相同的值
  • 找出数组里出现次数最多的,c 次,这个数分给 c 个子序列
  • 每个子序列长度至少为 K,那么必须满足 c ∗ K < = n c*K <= n cK<=n 数组长度
class Solution {
public: bool canDivideIntoSubsequences(vector
& nums, int K) {
unordered_map
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

  • 数组有序,不需要哈希map计数,见官方答案
class Solution {
public: bool canDivideIntoSubsequences(vector
& 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


我的CSDN

长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!

Michael阿明

转载地址:https://michael.blog.csdn.net/article/details/107575232 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode 1272. 删除区间
下一篇:LeetCode 410. 分割数组的最大值(极小极大化 二分查找 / DP)

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月24日 04时21分01秒