zoukankan      html  css  js  c++  java
  • LeetCode-Range Sum Query

    Given an integer array nums, find the sum of the elements between indices i and j (ij), 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:

      1. The array is only modifiable by the update function.
      2. You may assume the number of calls to update and sumRange function is distributed evenly.
     1 public class NumArray {
     2         private int[] tree;
     3         private int[] num;
     4 
     5         public NumArray(int[] nums) {
     6             tree = new int[nums.length];
     7             num = new int[nums.length];
     8             
     9             Arrays.fill(tree,0);
    10             Arrays.fill(num,0);
    11             for (int i=0;i<nums.length;i++){
    12                 update(i,nums[i]);
    13             }
    14         }
    15 
    16         void update(int i, int val) {
    17             int delta = val-num[i];
    18             num[i] = val;
    19             int ind = i+1;
    20 
    21             while (ind<=tree.length){
    22                 tree[ind-1] += delta;
    23                 ind += ind & (-ind);
    24             }
    25 
    26         }
    27 
    28         private int sum(int i){
    29             int ind = i+1;
    30             int sum = 0;
    31 
    32             while (ind>0){
    33                 sum += tree[ind-1];                
    34                 ind -= ind & (-ind);
    35             }
    36             return sum;
    37         }
    38 
    39         public int sumRange(int i, int j) {
    40             int a = sum(j);
    41             int b = sum(i-1);
    42             return a-b;
    43         }
    44         
    45         
    46     }
    47 
    48 
    49 // Your NumArray object will be instantiated and called as such:
    50 // NumArray numArray = new NumArray(nums);
    51 // numArray.sumRange(0, 1);
    52 // numArray.update(1, 10);
    53 // numArray.sumRange(1, 2);

    Solution: it is an entry-level problem about Binary Indexed Tree.

    Check BIT out: http://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/

  • 相关阅读:
    10 个雷人的注释,就怕你不敢用!
    Java 14 之模式匹配,非常赞的一个新特性!
    poj 3661 Running(区间dp)
    LightOJ
    hdu 5540 Secrete Master Plan(水)
    hdu 5584 LCM Walk(数学推导公式,规律)
    hdu 5583 Kingdom of Black and White(模拟,技巧)
    hdu 5578 Friendship of Frog(multiset的应用)
    hdu 5586 Sum(dp+技巧)
    hdu 5585 Numbers
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5328231.html
Copyright © 2011-2022 走看看