Leetcode 3355 Zero Array Transformation

题意:给定一个长度为 n的int数组以及一个2D array, 有一个query数组,每个数组里的数[Li, Ri]代表这个区间的子集区间的数都减1,求这个数组在经过这个query数组之后能否变成全部为0的数组

https://leetcode.com/problems/zero-array-transformation-i/description/

题解:用差分数组可以解决,计算经过这么多个query之后如果数组中所有的值都小于等于0,返回true

差分数组:长度和原数组保持一定

example: [8, 2, 3, 5]

查分: [8, -6, 1, 2]

如何还原:[8, 8+(-6), 8+(-6)+1, 8+(-6)+1 + 2]

差分数组求前缀和就是原答案,注意nums[0]特殊对待

cpp 复制代码
class Solution {
public:
    bool isZeroArray(vector<int>& nums, vector<vector<int>>& queries) {
        int n = nums.size();
        vector<int> sub(n, 0);
        vector<int> arr(n, 0);
        for(int i = 0; i < n; i++) {
            if(!i) {
                sub[i] = nums[0];
            } else {
                sub[i] = nums[i] - nums[i-1];
            }
        }
        
        
        for(auto query: queries) {
            sub[query[0]] -= 1;
            if(query[1]+1 < n) {
                sub[query[1] + 1] += 1;
            }
        }
        for(int i = 0; i < n; i++) {
            if(!i) {
                arr[i] = sub[0];
            } else {
                arr[i] = arr[i-1] + sub[i];
            }
            if ( arr[i] > 0 ) {
                return false;
            }
        }
        return true;
    }
};
相关推荐
2401_8588698014 分钟前
支持向量机
算法·机器学习·支持向量机
用户48221371677530 分钟前
深度学习——卷积神经网络
算法
DashingGuy34 分钟前
算法(keep learning)
java·数据结构·算法
兔兔西36 分钟前
【数据结构、java学习】数组(Array)
java·数据结构·算法
007php00736 分钟前
Go语言面试:传值与传引用的区别及选择指南
java·开发语言·后端·算法·面试·golang·xcode
小徐不徐说37 分钟前
数据结构基础之队列:数组/链表
c语言·数据结构·算法·链表·面试
fantasy_arch1 小时前
SVT-AV1 svt_aom_motion_estimation_kernel 函数分析
人工智能·算法·av1
星逝*2 小时前
LeetCode刷题-top100( 矩阵置零)
算法·leetcode·矩阵
zandy10112 小时前
LLM与数据工程的融合:衡石Data Agent的语义层与Agent框架设计
大数据·人工智能·算法·ai·智能体
max5006003 小时前
本地部署开源数据生成器项目实战指南
开发语言·人工智能·python·深度学习·算法·开源