(LeetCode 307) Range Sum Query - Mutable(Segment Tree)

Q:
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
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.

题意大致是,给你提供一个二维数组,然后求指定下标之间的数之和,已知数组中的值可以更新,并且更新和求和操作会被频繁调用

Solution;
别看这道题和上几道题相似,解法其实完全不一样, (LeetCode 303) Range Sum Query - Immutable
最原始的想法就是暴力遍历求和,不过想也不用想,当求和操作操作频繁调用,会超出给定时限。
并且,数组中的值会被频繁更新,我了解到的解决方法有Segement Tree(线段树),Binary Indexed Tree(树状数组) ,和平方根分解三种办法。树状数组真的是神作,很精巧的办法,也很高兴能够了解并学习这些数据结构。

我在这里提供线段树的解法,想了解树状数组的解法可以参考这篇博客:
(LeetCode 307) Range Sum Query - Mutable(树状数组讲解)

线段树,顾名思义,它的每一个结点代表一个区间。每个结点中包含的信息应该有该区间的起始下标 start ,结束下标 end ,左子树指针

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值