【LeetCode】线段树 segment-tree(共9题)+ 树状数组 binary-indexed-tree(共5题)

第一部分---线段树:https://leetcode.com/tag/segment-tree/  

【218】The Skyline Problem 

【307】Range Sum Query - Mutable 

【308】Range Sum Query 2D - Mutable 

【315】Count of Smaller Numbers After Self 

【493】Reverse Pairs 

【699】Falling Squares 

【715】Range Module 

【732】My Calendar III 

【850】Rectangle Area II 

 

第二部分---树状数组:https://leetcode.com/tag/binary-indexed-tree/

【218】The Skyline Problem 

【307】Range Sum Query - Mutable (2018年1月14日,学习BIT)

实现一个一维的树状数组模板。

 1 class NumArray {
 2 public:
 3     NumArray(vector<int> nums) {
 4         n = nums.size();
 5         this->nums.resize(n+1);
 6         bit.resize(n+1);
 7         for (int i = 1; i <= n; ++i) {
 8             this->nums[i] = nums[i-1];
 9             add(i, this->nums[i]);
10         }      
11     }
12     void update(int i, int val) {
13         add(i+1, val - nums[i+1]);
14         nums[i + 1] = val;   
15     }
16     int sumRange(int i, int j) {
17         ++i, ++j;
18         return sum(j) - sum(i-1);
19     }
20     int lowbit(int x) {
21         return x & -x;
22     }
23     void add(int x, int v) {
24         for (int i = x; i <= n; i += lowbit(i)) {
25             bit[i] += v;
26         }
27     }
28     int sum(int x) {
29         int ret = 0;
30         for (int i = x; i > 0; i -= lowbit(i)) {
31             ret += bit[i];
32         }
33         return ret;
34     }
35     vector<int> nums, bit;
36     int n;
37 };
38 
39 /**
40  * Your NumArray object will be instantiated and called as such:
41  * NumArray obj = new NumArray(nums);
42  * obj.update(i,val);
43  * int param_2 = obj.sumRange(i,j);
44  */
View Code

 

【308】Range Sum Query 2D - Mutable (2018年1月14日,学习BIT)

 

【315】Count of Smaller Numbers After Self 

【493】Reverse Pairs 

猜你喜欢

转载自www.cnblogs.com/zhangwanying/p/9964023.html
0条评论
添加一条新回复
  
今日推荐