LintCode_207 interval-sum-ii

Given an integer array in the construct method, implement two methods query(start, end) and modify(index, value):

  • For query(startend), return the sum from index start to index end in the given array.
  • For modify(indexvalue), modify the number in the given index to value
 Notice

We suggest you finish problem Segment Tree BuildSegment Tree Queryand Segment Tree Modify first.

Example

Given array A = [1,2,7,8,5].

  • query(0, 2), return 10.
  • modify(0, 4), change A[0] from 1 to 4.
  • query(0, 1), return 6.
  • modify(2, 1), change A[2] from 7 to 1.
  • query(2, 4), return 14.

没用线段树, 竟然蒙过关了,也是醉了:

思路是这样的, 先把0-i的sum算出来存起来, 然后只存改变的index和dif,正真计算的时候在把dif加上:


class Solution {
public:
   vector<long long> sum = {0};
   vector<int> A;
   vector<int> change;
   unordered_map<int, int> dif_value;

    /**
     * @param A: An integer vector
     */
    Solution(vector<int> A) {
        // write your code here
        this->A = A;
        int t = sum[0];
        for (int i = 0; i < A.size(); i++) {
            t+=A[i];
            sum.push_back(t);
        }
    }
    
    /**
     * @param start, end: Indices
     * @return: The sum from start to end
     */
    long long query(int start, int end) {
        // write your code here
        long long sum_dif_s = 0;
        long long sum_dif_e = 0;
        // for (int i = 0; i <change.size(); i++) {
        //     cout
        // }
        int prev_start = start - 1;
        for (int i = 0; i < change.size(); i++) {
            if (prev_start < change[i] && end <change[i]) {
                        break;
            }
            if (change[i] <= prev_start) {
                sum_dif_s+=dif_value[change[i]];
            }
            if (change[i] <= end) {
                sum_dif_e+=dif_value[change[i]];
            }
        }
        // cout<<sum_dif_s<<endl;
        // cout<<sum_dif_e<<endl;
        
        long long real_sum = (sum[end + 1] + sum_dif_e) - (sum[start] + sum_dif_s);
        
        return real_sum;
        
    }
    
    /**
     * @param index, value: modify A[index] to value.
     */
    void modify(int index, int value) {
        // write your code here
        //if (index < this->A.size())
        int dif = value - A[index];
        auto itr = lower_bound(change.begin(), change.end(), index);
        if (itr == change.end() || *itr != index) {
            change.insert(itr, index);
        }
        dif_value[index] = dif;
    }
};





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值