share my java solution(easy implementation version):


  • 0
    C
    public class NumArray {
        int[] TreeNodes;
        int len=0;
        public NumArray(int[] nums) {
            this.len=nums.length;
            TreeNodes=new int[2*nums.length];
            for(int i=0;i<nums.length;i++){
                TreeNodes[i+nums.length]=nums[i];
            }
            for(int i=nums.length-1;i>=0;i--){
                TreeNodes[i]=TreeNodes[i<<1]+TreeNodes[(i<<1)|1];
            }
        }
        
        public void update(int i, int val) {
            int dif=val-TreeNodes[i+len];
            i+=len;
             while(i>0){
                 TreeNodes[i]+=dif;
                 i>>=1;
             }
        }
        
        public int sumRange(int i, int j) {
            int sum=0;
            i+=len;
            j+=len;
            for(;i<=j;i>>=1,j>>=1){
                if((i&1)==1){
                    sum+=TreeNodes[i];
                    i++;
                }
                if((j&1)==0){
                    sum+=TreeNodes[j];
                    j--;
                }
            }
            return sum;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.