|
| 1 | +/** |
| 2 | + * 307. Range Sum Query - Mutable |
| 3 | + * https://leetcode.com/problems/range-sum-query-mutable/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given an integer array nums, handle multiple queries of the following types: |
| 7 | + * 1. Update the value of an element in nums. |
| 8 | + * 2. Calculate the sum of the elements of nums between indices left and right inclusive |
| 9 | + * where left <= right. |
| 10 | + * |
| 11 | + * Implement the NumArray class: |
| 12 | + * - NumArray(int[] nums) Initializes the object with the integer array nums. |
| 13 | + * - void update(int index, int val) Updates the value of nums[index] to be val. |
| 14 | + * - int sumRange(int left, int right) Returns the sum of the elements of nums between |
| 15 | + * indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]). |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number[]} nums |
| 20 | + */ |
| 21 | +var NumArray = function(nums) { |
| 22 | + this.n = nums.length; |
| 23 | + this.tree = new Array(2 * this.n); |
| 24 | + |
| 25 | + for (let i = 0; i < this.n; i++) { |
| 26 | + this.tree[this.n + i] = nums[i]; |
| 27 | + } |
| 28 | + |
| 29 | + for (let i = this.n - 1; i > 0; i--) { |
| 30 | + this.tree[i] = this.tree[i * 2] + this.tree[i * 2 + 1]; |
| 31 | + } |
| 32 | +}; |
| 33 | + |
| 34 | +/** |
| 35 | + * @param {number} index |
| 36 | + * @param {number} val |
| 37 | + * @return {void} |
| 38 | + */ |
| 39 | +NumArray.prototype.update = function(index, val) { |
| 40 | + let position = this.n + index; |
| 41 | + this.tree[position] = val; |
| 42 | + |
| 43 | + while (position) { |
| 44 | + let left = position; |
| 45 | + let right = position; |
| 46 | + if (position % 2 === 0) { |
| 47 | + right = position + 1; |
| 48 | + } else { |
| 49 | + left = position - 1; |
| 50 | + } |
| 51 | + this.tree[position >> 1] = this.tree[left] + this.tree[right]; |
| 52 | + position >>= 1; |
| 53 | + } |
| 54 | +}; |
| 55 | + |
| 56 | +/** |
| 57 | + * @param {number} left |
| 58 | + * @param {number} right |
| 59 | + * @return {number} |
| 60 | + */ |
| 61 | +NumArray.prototype.sumRange = function(left, right) { |
| 62 | + let sum = 0; |
| 63 | + let l = this.n + left; |
| 64 | + let r = this.n + right + 1; |
| 65 | + |
| 66 | + while (l < r) { |
| 67 | + if (l % 2 == 1) { |
| 68 | + sum += this.tree[l++]; |
| 69 | + } |
| 70 | + if (r % 2 == 1) { |
| 71 | + sum += this.tree[--r]; |
| 72 | + } |
| 73 | + l >>= 1; |
| 74 | + r >>= 1; |
| 75 | + } |
| 76 | + |
| 77 | + return sum; |
| 78 | +}; |
0 commit comments