首页 > 其他 > 详细

LeetCode Range Sum Query - Mutable

时间:2016-03-06 06:37:19      阅读:132      评论:0      收藏:0      [点我收藏+]

原题链接在这里:https://leetcode.com/problems/range-sum-query-mutable/

题目:

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:

  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.

题解:

Range Sum Query - Mutable类似,用到了二维binary index tree. 

Time Complexity: builder O(mnlogmn). update O(logmn). sumRange O(logmn). Space : O(mn).

AC Java:

 1 public class NumArray {
 2     int [] BIT;
 3     int [] nums;
 4     
 5     public NumArray(int[] nums) {
 6         if(nums == null || nums.length == 0){
 7             return;
 8         }
 9         BIT = new int[nums.length + 1];
10         this.nums = new int[nums.length];
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 diff = val - nums[i];
18         nums[i] = val;
19         for(int j = i+1; j<BIT.length; j += (j&-j)){
20             BIT[j] += diff;
21         }
22     }
23 
24     public int sumRange(int i, int j) {
25         return getSum(j+1) - getSum(i);
26     }
27     private int getSum(int i){
28         int sum = 0;
29         while(i > 0){
30             sum += BIT[i];
31             i -= (i & -i);
32         }
33         return sum;
34     }
35 }
36 
37 
38 // Your NumArray object will be instantiated and called as such:
39 // NumArray numArray = new NumArray(nums);
40 // numArray.sumRange(0, 1);
41 // numArray.update(1, 10);
42 // numArray.sumRange(1, 2);

 

LeetCode Range Sum Query - Mutable

原文:http://www.cnblogs.com/Dylan-Java-NYC/p/5246473.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!