题目链接: https://leetcode.com/problems/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:
Given: 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 ]
思路: 隐约记得这题好像是在13年南理工ACM比赛的一题, 当时感觉应该像是线段树, 不过没做出来. 当时太水了, 现在依然很水!
在这题中没必要每次把区间的每一个值都更新, 只需要更新起点和终点后的一点即可. 也就是说把增加的值放在起点, 终点后的一点减去增加的值, 这样再扫描的时候把之前累加的和作为最终值即可.
代码如下:
class Solution {
public:
vector<int> getModifiedArray(int length, vector<vector<int>>& updates) {
vector<int> ans(length, 0);
for(auto vec1: updates)
{
int left = vec1[0], right = vec1[1], val = vec1[2];
ans[left] += val;
if(right+1 < length) ans[right+1] -= val;
}
for(int i = 0, sum = 0; i < length; i++)
{
sum += ans[i];
ans[i] = sum;
}
return ans;
}
};
参考: https://discuss.leetcode.com/topic/49691/java-o-k-n-time-complexity-solution