资讯专栏INFORMATION COLUMN

[LintCode/LeetCode] Range Addition

endless_road / 1231人阅读

Problem

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]
]

return [-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 ]

Solution
public class Solution {
    /**
     * @param length: the length of the array
     * @param updates: update operations
     * @return: the modified array after all k operations were executed
     */
    public int[] getModifiedArray(int length, int[][] updates) {
        // Write your code here
        
        int[] res = new int[length];
        Arrays.fill(res, 0);
        
        for (int[] update: updates) {
            for (int i = update[0]; i <= update[1]; i++) {
                res[i] += update[2];
            }
        }
        return res;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/71674.html

相关文章

  • [LintCode/LeetCode] Search for a Range [左右边界法/一次循环

    摘要:首先,建立二元结果数组,起点,终点。二分法求左边界当中点小于,移向中点,否则移向中点先判断起点,再判断终点是否等于,如果是,赋值给。 Problem Given a sorted array of n integers, find the starting and ending position of a given target value. If the target is not...

    zhangrxiang 评论0 收藏0
  • [LintCode/LeetCode] Combinations

    摘要:题目为求从到的自然数里取个数的所有组合全集。使用递归的模板,建立函数。模板如下也可以不建立新的,而是递归调用之后删去中最后一个元素 Problem Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. Example For example,If n = 4 a...

    Raaabbit 评论0 收藏0
  • [LintCode/LeetCode] Word Break

    Problem Given a string s and a dictionary of words dict, determine if s can be break into a space-separated sequence of one or more dictionary words. Example Given s = lintcode, dict = [lint, code]. R...

    dunizb 评论0 收藏0
  • [LintCode/LeetCode] First Unique Character in a S

    Problem Given a string, find the first non-repeating character in it and return its index. If it doesnt exist, return -1. Example Given s = lintcode, return 0. Given s = lovelintcode, return 2. Tags A...

    Xufc 评论0 收藏0
  • [LintCode/LeetCode] Find Median From / Data Stream

    摘要:建立两个堆,一个堆就是本身,也就是一个最小堆另一个要写一个,使之成为一个最大堆。我们把遍历过的数组元素对半分到两个堆里,更大的数放在最小堆,较小的数放在最大堆。同时,确保最大堆的比最小堆大,才能从最大堆的顶端返回。 Problem Numbers keep coming, return the median of numbers at every time a new number a...

    zxhaaa 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<