您的位置:首页 > 产品设计 > UI/UE

leetcode笔记:Range Sum Query - Mutable

2016-01-21 01:06 330 查看
一. 题目描述

Given an integer array
nums
, find the sum of the elements between indices
i
and
j
(i ≤ j)
, inclusive.

The
update(i, val)
function modifies
nums
by updating the element at index
i
to
val
.

Example:

Given
nums = [1, 3, 5]


[code]sumRange(0, 2) -> 9
update(1, 2)
sumRange(0, 2) -> 8


Note:

The array is only modifiable by the update function.

You may assume the number of calls to update and sumRange function is distributed evenly.

二. 题目分析

题目在Range Sum Query - Immutable一题的基础上增加的难度,要求在输入数组nums后,能够修改数组的元素,每次只修改一个元素。同样要实现求数组的某个区间和的功能。

如果在/article/3627862.html 一题的做法上稍加改进,是可以实现功能的,但是会超时。

这时阅读了一些文章后才发现原来经典的做法(包括前一题)是使用树状数组来维护这个数组nums,其插入和查询都能做到O(logn)的复杂度,十分巧妙。

关于树状数组,以下博文描述得很好:

http://blog.csdn.net/int64ago/article/details/7429868

三. 示例代码

[code]// 超时
class NumArray {
public:
    NumArray(vector<int> &nums) {
        if (nums.empty()) return;
        else
        {
            sums.push_back(nums[0]);
            //求得给定数列长度
            int len = nums.size();
            for (int i = 1; i < len; ++i)
                sums.push_back(sums[i - 1] + nums[i]);
        }
    }

    void update(int i, int val) {
        for (int k = i; k < nums.size(); ++k)
            sums[k] += (val - nums[i]);
        nums[i] = val;
    }

    int sumRange(int i, int j) {
        return sums[j] - sums[i - 1];
    }

private:
    vector<int> nums;
    //存储数列和
    vector<int> sums;
};

// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.update(1, 10);
// numArray.sumRange(1, 2);


[code]// 使用树状数组实现的代码AC,复杂度为O(logn)
class NumArray {
private:
    vector<int> c;
    vector<int> m_nums;
public:
    NumArray(vector<int> &nums) {
        c.resize(nums.size() + 1);
        m_nums = nums;
        for (int i = 0; i < nums.size(); i++){
            add(i + 1, nums[i]);
        }
    }

    int lowbit(int pos){
        return pos&(-pos);
    }

    void add(int pos, int value){
        while (pos < c.size()){
            c[pos] += value;
            pos += lowbit(pos);
        }
    }
    int sum(int pos){
        int res = 0;
        while (pos > 0){
            res += c[pos];
            pos -= lowbit(pos);
        }
        return res;
    }

    void update(int i, int val) {
        int ori = m_nums[i];
        int delta = val - ori;
        m_nums[i] = val;
        add(i + 1, delta);
    }

    int sumRange(int i, int j) {
        return sum(j + 1) - sum(i);
    }
};
// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.update(1, 10);
// numArray.sumRange(1, 2);


四. 小结

之前只是听过,这是第一次使用树状数组,这是维护数组的一个很好的思想,需要深入学习!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: