每日一题(leetcode2009):使数组连续的最小操作数--滑动窗口

从相反面考虑,一条已知长度的线段最多能覆盖多少数值,最先用长度减一下就行。线段覆盖问题用滑动窗口就行。代码如下:

cpp 复制代码
class Solution {
public:
    int minOperations(vector<int>& nums) {
        int len=nums.size();
        sort(nums.begin(),nums.end());
        int m=unique(nums.begin(),nums.end()) -nums.begin();
        int left=0;
        int ans=0;
        for(int i=0;i<m;i++)
        {
            while(nums[left]<nums[i]-len+1){
                left++;
            }
            ans=max(i-left+1,ans);
        }
        return len-ans;
    }
};

其中 int m=unique(nums.begin(),nums.end()) -nums.begin();为原地去重代码。unique(nums.begin(),nums.end())返回的是排序好的数的后面一个数,所以减去开头就是去重序列的长度。

相关推荐
Zane19941 小时前
暴力字符串匹配失配就要把文本指针往回拉,KMP凭什么能让它一直往前走
算法
Tim_102 小时前
【LeetCode】338、比特位计数
c++·算法·leetcode
木子算法2 小时前
不是重心也不是中点:费马—韦伯点、它的最优性条件与迭代求解
人工智能·算法·目标跟踪
tryxr3 小时前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_33 小时前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Selvaggia3 小时前
DMD(Distribution Matching Distillation,分布匹配蒸馏)
算法
Navigator_Z4 小时前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.4 小时前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
开开心心就好4 小时前
安卓手写文字生成工具,多种纸张一直免费
网络·网络协议·tcp/ip·leetcode·智能手机·电脑·模拟退火算法
All for pursuit.4 小时前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode