资讯专栏INFORMATION COLUMN

370. Range Addition

shuibo / 1525人阅读

摘要:题目解法这题与算法无关,是个数学题。思想是把所有需要相加的值存在第一个数,然后把这个范围的最后一位的下一位减去这个这样我所以这个范围在求最终值的时候,都可以加上这个,而后面的数就不会加上。

题目:
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 ]

解法:
这题与算法无关,是个数学题。思想是把所有需要相加的值存在第一个数,然后把这个范围的最后一位的下一位减去这个inc, 这样我所以这个范围在求最终值的时候,都可以加上这个inc,而后面的数就不会加上inc。

public int[] getModifiedArray(int length, int[][] updates) {
    int[] result = new int[length];
    for (int i = 0; i < updates.length; i++) {
        int start = updates[i][0], end = updates[i][1];
        int inc = updates[i][2];
        result[start] += inc;
        if (end < length - 1) {
            result[end + 1] -= inc;
        }
    }
    
    int sum = 0;
    for (int i = 0; i < length; i++) {
        sum += result[i];
        result[i] = sum;
    }
    return result;
}

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

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

相关文章

  • 370. Range Addition

    摘要:题目链接这道题暴力法是可以的,每次把所有在到之间的值都更新一遍,不过题目要求要,所以其实每次更新只能用的时间。如果结束的地方就在末尾,那就不更新。 370. Range Addition 题目链接:https://leetcode.com/problems... 这道题暴力法是可以的,每次把所有在start到end之间的值都更新一遍,不过题目要求要O(k+n),所以其实每次更新只能用c...

    bluesky 评论0 收藏0
  • [LintCode/LeetCode] Range Addition

    Problem Assume you have an array of length n initialized with all 0s and are given k update operations. Each operation is represented as a triplet: [startIndex, endIndex, inc] which increments each el...

    endless_road 评论0 收藏0
  • Java实现通过日语元音ae的发音曲线分类9个发音者

    摘要:需要对个人的日语元音的发音分析,然后根据分析确定名发音者。九个发音者发出两个日本元音先后。其中每块数据中包含的行数为到不等,每行代表着发音者的一个时间帧。 业务理解(Business Understanding) 该业务是分类问题。需要对9个人的日语元音ae的发音分析,然后根据分析确定9名发音者。ae.train文件是训练数据集,ae.test文件是用来测试训练效果的,size_ae...

    lncwwn 评论0 收藏0
  • 【开发语言】PHP、Java、C语言的编译执行过程

    摘要:效率比较低,依赖解释器,跨平台性好语言编译执行过程下面都是鸟哥博客的内容深入理解原理之引擎对这个文件进行词法分析,语法分析,编译成,然后执行。 编译型语言和解释型语言 从PHP,Java和C语言的编译执行过程可以先解释下编译型语言和解释型语言。 编译型语言 程序在执行之前需要一个专门的编译过程,把程序编译成为机器语言的文件,运行时不需要重新翻译,直接使用编译的结果就行了。程序执行效率高...

    gnehc 评论0 收藏0

发表评论

0条评论

shuibo

|高级讲师

TA的文章

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