码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Range Sum Query - Mutable"

时间:2015-11-19 07:04:58      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

Fenwick tree can do this job.

class NumArray {
    vector<int> in;
    vector<int> ft;

    int query(int i)
    { 
        i += 1;
        i = min(i, int(ft.size() - 1));
        int s = 0;  
        for (; i > 0; i -= (i & -i)) 
            s += ft[i];  
        return s; 
    }
    void init(int i, int v) {
    i += 1;
    for (; i < ft.size(); i += (i & -i))
            ft[i] += v;
    }

public:
    NumArray(vector<int> &nums) {
    in = nums;
        int n = nums.size();
    ft.assign(n + 1, 0);
    for(int i = 0; i < n; i ++)
        init(i, nums[i]);
    }

    void update(int i, int v) {
    int d = v - in[i];
    in[i] = v;
    i += 1;
    for (; i < ft.size(); i += (i & -i))
            ft[i] += d;
    }

    int sumRange(int i, int j) {
        return query(j) - (i ? query(i - 1) : 0);
    }
};

LeetCode "Range Sum Query - Mutable"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4976464.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!