其他分享
首页 > 其他分享> > leetcode [307]Range Sum Query - Mutable

leetcode [307]Range Sum Query - Mutable

作者:互联网

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.

题目大意:

得到数组给定范围内的和

解法:

我就是很简单的解法,并没有做优化。

java:

class NumArray {
    private int[] nums;
        
    public NumArray(int[] nums) {
        this.nums=new int[nums.length];
        for (int i=0;i<nums.length;i++) 
            this.nums[i]=nums[i];
    }

    public void update(int i, int val) {
        this.nums[i]=val;
    }

    public int sumRange(int i, int j) {
        int sum=0;
        for (int index=i;index<=j;index++){
            sum+=this.nums[index];
        }
        return sum;
    }
}

 看网上的解法还可以使用树状数组来做https://blog.csdn.net/Small_Orange_glory/article/details/81290634,这种数据结构真的很巧妙,巧妙运用了数字二进制。

class NumArray {
    private int[] nums;
    private int[] BIT;
    private int n;

    public NumArray(int[] nums) {
        this.nums=nums;
        n= nums.length;
        this.BIT=new int[n+1];
        for (int i=0;i<n;i++)
            init(i,nums[i]);
    }

    private void init(int i,int val){
        i++;
        while(i<=n){
            BIT[i]+=val;
            i+=(i&(-i));
        }
    }

    public void update(int i, int val) {
        int diff=val-nums[i];
        nums[i]=val;
        init(i,diff);
    }

    private int sum(int i){
        int sum=0;
        i++;
        while(i>0){
            sum+=BIT[i];
            i-=(i&(-i));
        }
        return sum;
    }

    public int sumRange(int i, int j) {
        return sum(j)-sum(i-1);
    }
}

标签:nums,int,sum,update,private,307,Range,sumRange,Sum
来源: https://www.cnblogs.com/xiaobaituyun/p/10870917.html