LeetCode 370. Range Addition

16 篇文章 0 订阅
9 篇文章 0 订阅

原题网址: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:

  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.
方法一:类似城市天际线问题,使用最小堆来维护当前的范围。

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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值