当前位置: 面试刷题>> 范围加法 (经典算法题500道)


完整题目描述

题目:范围加法(Range Addition)

给定一个初始化为全零的整数数组nums,和一个二维数组operations,其中每个操作operations[i]包含两个整数a[i]b[i],表示对数组nums进行如下操作:将索引范围[a[i], b[i]](包括a[i]b[i])内的所有元素都加上c,其中c是操作的第三个参数(题目简化处理,这里默认c为固定值,如c=1,但在实际应用中c可以是任何整数)。

要求:

  1. 实现一个函数,该函数接收numsoperations作为输入,并返回进行所有操作后的nums数组。
  2. 考虑到效率问题,尽量使用差分数组(Difference Array)或其他高效算法来减少不必要的重复操作。

示例

输入

nums = [0, 0, 0, 0, 0]
operations = [[1, 2, 1], [3, 5, 2]]

这里默认每个操作的c值为操作数组中未明确给出的第三个数,但为了简化题目,我们这里默认所有操作的c值均为1

输出

[1, 2, 2, 3, 3]

解释:

  • 第一个操作[1, 2, 1]:将索引12(包括)的元素都加1,即nums[1]nums[2]各加1
  • 第二个操作[3, 5, 2]:但按简化处理,我们仅加1,因此将索引35(包括)的元素都加1,即nums[3]nums[4]nums[5]各加1

示例代码

PHP

function rangeAddition(array $nums, array $operations) {
    $n = count($nums);
    $diff = array_fill(0, $n, 0); // 初始化差分数组

    foreach ($operations as $op) {
        $a = $op[0];
        $b = $op[1];
        $c = 1; // 假设c总是1
        $diff[$a] += $c;
        if ($b + 1 < $n) {
            $diff[$b + 1] -= $c;
        }
    }

    // 根据差分数组恢复原始数组
    $result = array_fill(0, $n, 0);
    $result[0] = $diff[0];
    for ($i = 1; $i < $n; $i++) {
        $result[$i] = $result[$i - 1] + $diff[$i];
    }

    return $result;
}

// 示例
$nums = [0, 0, 0, 0, 0];
$operations = [[1, 2, 1], [3, 5, 2]]; // 注意:实际实现中只使用了前两个参数
$result = rangeAddition($nums, $operations);
print_r($result);

注意: PHP示例中,由于PHP本身不直接支持操作中的第三个参数c的动态读取(题目已简化为默认c=1),故在示例中未直接使用。

Python

def rangeAddition(nums, operations):
    n = len(nums)
    diff = [0] * n

    for a, b in operations:
        c = 1  # 假设c总是1
        diff[a] += c
        if b + 1 < n:
            diff[b + 1] -= c

    # 根据差分数组恢复原始数组
    result = [0] * n
    result[0] = diff[0]
    for i in range(1, n):
        result[i] = result[i - 1] + diff[i]

    return result

# 示例
nums = [0, 0, 0, 0, 0]
operations = [[1, 2], [3, 5]]  # 注意:只传递前两个参数
result = rangeAddition(nums, operations)
print(result)

JavaScript

function rangeAddition(nums, operations) {
    const n = nums.length;
    const diff = new Array(n).fill(0);

    for (const [a, b] of operations) {
        const c = 1; // 假设c总是1
        diff[a] += c;
        if (b + 1 < n) {
            diff[b + 1] -= c;
        }
    }

    // 根据差分数组恢复原始数组
    const result = new Array(n).fill(0);
    result[0] = diff[0];
    for (let i = 1; i < n; i++) {
        result[i] = result[i - 1] + diff[i];
    }

    return result;
}

// 示例
const nums = [0, 0, 0, 0, 0];
const operations = [[1, 2], [3, 5]]; // 注意:只传递前两个参数
const result = rangeAddition(nums, operations);
console.log(result);

码小课:以上是使用PHP、Python和JavaScript编写的范围加法问题的示例代码。在码小课网站中,你可以找到更多关于算法和数据结构的相关内容,帮助你深入学习和掌握编程技能。

推荐面试题