leetcode 3510

3510: 移除最小数对使数组有序Ⅱ

题干同 leetcode 3507

区别:(数据规模增大)

  • 1 <= nums.length <= 50 (3507)
  • -1000 <= nums[i] <= 1000
  • 1 <= nums.length <= 105 (3510)
  • -109 <= nums[i] <= 109

暴力模拟方法仅针对小数据范围,用于本题会超时。

思路:懒删除堆+数组模拟双向链表(详解见leetcode 3507)

复制代码
class Solution {
public:
    int minimumPairRemoval(vector<int>& nums) {
        int n=nums.size();
        priority_queue<pair<long long,int>,vector<pair<long long,int>>,greater<>> pq;
        int dec=0;
        for(int i=0;i<n-1;i++){
            int x=nums[i],y=nums[i+1];
            if(x>y) dec++;
            pq.emplace(x+y,i);
        }
        vector<int> left(n+1),right(n);
        ranges::iota(left,-1);
        ranges::iota(right,1);

        vector<long long> a(nums.begin(),nums.end());
        int ans=0;
        while(dec){
            ans++;
            while(right[pq.top().second]>=n || pq.top().first!=a[pq.top().second]+a[right[pq.top().second]]){
                pq.pop();
            }
            auto[s,i]=pq.top();
            pq.pop();

            int nxt=right[i];
            dec-=a[i]>a[nxt];
            int pre=left[i];
            if(pre>=0){
                dec-=a[pre]>a[i];
                dec+=a[pre]>s;
                pq.emplace(a[pre]+s,pre);
            }
            int nxt2=right[nxt];
            if(nxt2<n){
                dec-=a[nxt]>a[nxt2];
                dec+=s>a[nxt2];
                pq.emplace(s+a[nxt2],i);
            }
            a[i]=s;
            int l=left[nxt],r=right[nxt];
            right[l]=r;
            left[r]=l;
            right[nxt]=n;
        }

        return ans;
    }
};
相关推荐
m0_639906947 小时前
Redis入门|五种数据结构、使用场景、持久化RDB&AOF
数据结构·数据库·redis
ZhengEnCi8 小时前
Agent 架构怎么选:从单 Agent 到多 Agent 编排的选型决策指南
算法·架构
秋天的怀念_David9 小时前
第二十二夜 · 数字迷雾
java·程序人生·算法
Pniubi9 小时前
力扣283移动零(双指针法)
算法·leetcode·职场和发展
hhb_6189 小时前
大模型落地三重优化实战
人工智能·算法·机器学习
云和数据.ChenGuang9 小时前
光哥说Python RAG 系统需要哪些评估指标:从检索到生成的全链路评测指南
网络·人工智能·python·算法·langchain
2601_9707038311 小时前
工业除湿机租赁:把一份租金合同拆开看
大数据·数据结构·算法·数据库架构·推荐算法
心中有你021411 小时前
Java实现Dijkstra最短路径算法(邻接表 + 优先队列)
java·数据库·算法
ZhengEnCi12 小时前
同样的模型,为什么本地和云 API 差别那么大:量化精度、聊天模板与采样参数的三大元凶
人工智能·算法·llm
Flynn Liang12 小时前
RAG 答非所问/幻觉怎么破?Spring AI QuestionAnswerAdvisor 召回优化实战(TopK/重排/混合检索)
人工智能·算法·spring·rag·幻觉·springai