370. Range Addition


Assume you have an array of length n initialized with all 0’s and are given k update operations.

Each operation is represented as a triplet: [startIndex, endIndex, inc] which increments each element of subarray A[startIndex … endIndex] (startIndex and endIndex inclusive) with inc.

Return the modified array after all k operations were executed.

Example:

Input: length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]]
Output: [-2,0,3,5,3]

Explanation:

Initial state:
[0,0,0,0,0]

After applying operation [1,3,2]:
[0,2,2,2,0]

After applying operation [2,4,3]:
[0,2,5,5,3]

After applying operation [0,2,-2]:
[-2,0,3,5,3]

Hint:

  1. Thinking of using advanced data structures? You are thinking it too complicated.
  2. For each update operation, do you really need to update all elements between i and j?
  3. Update only the first and end element is sufficient.
  4. The optimal time complexity is O(k + n) and uses O(1) extra space.

方法0:

方法1:

官方题解:https://leetcode.com/problems/range-addition/solution/

思路:

根据hint, 对每一次range addition只需要改动startIdx 成为result[startIdx] += val, 同时改动endIdx成为result[endIdx + 1] -= val。为什么要这么做?

Intuition

There is only one read query on the entire range, and it occurs at the end of all update queries. Additionally, the order of processing update queries is irrelevant.

Cumulative sums or partial_sum operations apply the effects of past elements to the future elements in the sequence.

也就是说,最后会利用prefix sum的累加性质把+val的效果扩散到startIdx以后。那么就需要在endIdx + 1 及其以后的位置抵消掉这个effect,也就是从endIdx + 1开始-val。那么最后求prefic的结果即可。

易错点

  1. 边界处理

Complexity

Time complexity: O(n+k). Each of the k update operations is done in constant O(1) time. The final cumulative sum transformation takes O(n) time always.

Space complexity : O(1). No extra space required.

class Solution {
public:
    vector<int> getModifiedArray(int length, vector<vector<int>>& updates) {
        vector<int> result(length + 1, 0);
        for (auto a: updates){
            result[a[0]] += a[2];
            result[a[1] + 1] -= a[2];
        }
        for (int i = 1; i < length; i++){
            result[i] = result[i - 1] + result[i];
        }
        
        result.pop_back();
        return result;
    }
};

二刷:


class Solution {
public:
    vector<int> getModifiedArray(int length, vector<vector<int>>& updates) {
        vector<int> nums(length, 0);
        for (auto v: updates) {
            nums[v[0]] += v[2];
            if (v[1] != length - 1) {
                nums[v[1] + 1] -= v[2];
            }
        }
        for (int i = 1; i < length; i++) {
            nums[i] = nums[i - 1] + nums[i];
        }
        return nums;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Sure, I can help you with that. Here's the code in Python using matplotlib and numpy libraries: ```python import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # Define the function def f(x, y): return 2*x**2 + y**2 # Define the range of t t = np.linspace(-3, 3, 100) # Calculate the x and y values x = np.sin(3*t) y = np.cos(3*t) # Calculate the z values z = f(x, y) # Create a meshgrid for the x and y values X, Y = np.meshgrid(x, y) # Create a figure and three subplots for the different types of plots fig = plt.figure(figsize=(12, 6)) ax1 = fig.add_subplot(2, 3, 1, projection='3d') ax1.plot_wireframe(X, Y, z) ax1.set_xlabel('X') ax1.set_ylabel('Y') ax1.set_zlabel('Z') ax1.set_title('3D Mesh Graph') ax2 = fig.add_subplot(2, 3, 2, projection='3d') ax2.plot_surface(X, Y, z, cmap='viridis') ax2.set_xlabel('X') ax2.set_ylabel('Y') ax2.set_zlabel('Z') ax2.set_title('3D Surface Graph') ax3 = fig.add_subplot(2, 3, 3, projection='3d') ax3.plot_surface(X, Y, z, cmap='viridis') ax3.contour(X, Y, z, zdir='z', offset=-1, cmap='viridis') ax3.set_xlabel('X') ax3.set_ylabel('Y') ax3.set_zlabel('Z') ax3.set_title('3D Surface Graph with Contour Lines') # Create a 2D sectional view graph for x=1 x1 = 1 y1 = np.linspace(-1.2, 1.2, 100) z1 = f(x1, y1) ax4 = fig.add_subplot(2, 3, 4) ax4.plot(y1, z1) ax4.set_xlabel('Y') ax4.set_ylabel('Z') ax4.set_title('2D Sectional View Graph for x=1') plt.show() ``` This code will generate a figure with six subplots. The first three subplots are the 3D mesh graph, 3D surface graph, and 3D surface graph with contour lines, respectively. The fourth subplot is the 2D sectional view graph for x=1. The ranges of the x and y axes are both [-1.2, 1.2], and the range of t is set to [-3, 3].

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值