美文网首页
307. Range Sum Query - Mutable解题

307. Range Sum Query - Mutable解题

作者: 黑山老水 | 来源:发表于2019-05-19 16:49 被阅读0次

Description:

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]

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

Link:

https://leetcode.com/problems/range-sum-query-mutable/

解题方法:

  1. Brute force is very straight forward, and pretty easy to implement.
  2. Segment tree:
    We can use an array to store our segment tree.
    Check 小fu's video on youtube

Time Complexity:

Brute force: n^2
Segment tree: nLogn

完整代码:

class NumArray {
    vector<int> tree;
    int size;
public:
    NumArray(vector<int>& nums) {
        size = nums.size();
        if(!size)
            return;
        tree = vector<int>(size * 2);
        // Build the segment tree.
        for(int i = 0; i < size; i++) {
            tree[size + i] = nums[i];
        }
        int i = size - 1;
        while(i >= 1) {
            tree[i] = tree[i * 2] + tree[i * 2 + 1];
            i--;
        }
    }
    
    void update(int i, int val) {
        if(i >= size)
            return;
        int index = i + size;
        int delt = val - tree[index];
        while(index > 0) {
            tree[index] += delt;
            index /= 2;
        }
    }
    
    int sumRange(int i, int j) {
        if(i == j)
            return tree[size + i];
        int low, high;
        if(i > j) {
            low = j + size;
            high = i + size;
        } else {
            low = i + size;
            high = j + size;
        }
        int sum = 0;
        // low <= high not low < high, this is very important!!!
        while(low <= high) {
            if(low % 2 != 0) {
                sum += tree[low++];
            }
            if(high % 2 == 0) {
                sum += tree[high--];
            }
            low /= 2;
            high /= 2;
        }
        // While low == high, we will always calculate one of em into sum during loop. 
        // So we dont need to add extra tree[low or high] here.
        // sum += tree[low];
        return sum;
    }
};

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray* obj = new NumArray(nums);
 * obj->update(i,val);
 * int param_2 = obj->sumRange(i,j);
 */

相关文章

网友评论

      本文标题:307. Range Sum Query - Mutable解题

      本文链接:https://www.haomeiwen.com/subject/axjqzqtx.html