题目:
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 ]
思路:
这道题目的直观解法很容易想到,就是每次更新区间内的所有元素。但是这种算法肯定是无法通过面试的。其实我们每次没必要把区间内的每个值都更新,只需要更新起点和终点后的一点即可。这样做的好处是:因为我们把增加的值放在了起点,而终点后一点相应减去了增加的值,所以再扫描的时候,把之前累加的和作为最终值即可。是不是很巧妙?
算法的时间复杂度是O(k) + O(n),其中k是更新的次数,n是数组的长度。空间复杂度是O(1)。
代码:
class Solution {
public:
vector<int> getModifiedArray(int length, vector<vector<int>>& updates) {
vector<int> sums(length, 0);
for(auto val : updates) {
sums[val[0]] += val[2];
if(val[1] < length - 1) {
sums[val[1] + 1] -= val[2];
}
}
int sum = 0;
for(int i = 0; i < length; ++i) {
sum += sums[i];
sums[i] = sum;
}
return sums;
}
};
本文介绍了一种高效解决数组批量更新问题的方法。面对大量的更新操作,直接更新每个元素将导致效率低下。文章提出一种巧妙的解决方案,只需更新区间的起始和结束位置附近的元素,大大提升了算法效率。
1046

被折叠的 条评论
为什么被折叠?



