原题网址: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 ]
Hint:
- Thinking of using advanced data structures? You are thinking it too complicated.
- For each update operation, do you really need to update all elements between i and j?
- Update only the first and end element is sufficient.
- The optimal time complexity is O(k + n) and uses O(1) extra space.
public class Solution {
public int[] getModifiedArray(int length, int[][] updates) {
Arrays.sort(updates, new Comparator<int[]>() {
@Override
public int compare(int[] seg1, int[] seg2) {
return Integer.compare(seg1[0], seg2[0]);
}
});
PriorityQueue<Integer> heap = new PriorityQueue<Integer>(new Comparator<Integer>() {
@Override
public int compare(Integer i1, Integer i2) {
return Integer.compare(updates[i1][1], updates[i2][1]);
}
});
int[] results = new int[length];
int j = 0;
int sum = 0;
for(int i = 0; i < length; i++) {
while (!heap.isEmpty() && updates[heap.peek()][1] < i) {
int p = heap.poll();
sum -= updates[p][2];
}
while (j < updates.length && i >= updates[j][0]) {
sum += updates[j][2];
heap.offer(j);
j++;
}
results[i] = sum;
}
return results;
}
}
方法二:将区间转换为一种加减的动态,方法太牛了,看论坛网友做的。
public class Solution {
public int[] getModifiedArray(int length, int[][] updates) {
int[] results = new int[length];
for(int[] update : updates) {
results[update[0]] += update[2];
if (update[1] + 1 < length) results[update[1] + 1] -= update[2];
}
int value = 0;
for(int i = 0; i < length; i++) {
value += results[i];
results[i] = value;
}
return results;
}
}

本文介绍了一种在数组上执行批量区间更新操作的高效算法。通过两种方法实现:一是使用最小堆维护当前区间,二是采用巧妙的动态加减策略简化计算过程。最终返回经过所有更新操作后的数组状态。
1035

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



