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;
    }
};
相关推荐
sali-tec2 小时前
C# 基于halcon的视觉工作流-章66 四目匹配
开发语言·人工智能·数码相机·算法·计算机视觉·c#
小明说Java2 小时前
常见排序算法的实现
数据结构·算法·排序算法
行云流水20193 小时前
编程竞赛算法选择:理解时间复杂度提升解题效率
算法
smj2302_796826524 小时前
解决leetcode第3768题.固定长度子数组中的最小逆序对数目
python·算法·leetcode
cynicme5 小时前
力扣3531——统计被覆盖的建筑
算法·leetcode
core5125 小时前
深度解析DeepSeek-R1中GRPO强化学习算法
人工智能·算法·机器学习·deepseek·grpo
mit6.8245 小时前
计数if|
算法
a伊雪6 小时前
c++ 引用参数
c++·算法
圣保罗的大教堂6 小时前
leetcode 3531. 统计被覆盖的建筑 中等
leetcode