Java solution, 3ms


  • 0
    F
        private int[] nums;
        public NumArray(int[] nums) {
            this.nums = nums;
            int length = this.nums.length;
            for (int i = 1; i < length; i++) {
                nums[i] += nums[i - 1];
            }
        }
    
        public int sumRange(int i, int j) {
            if (i == 0) return nums[j];
            return nums[j] - nums[i - 1];
        }
    }
    
    
    // Your NumArray object will be instantiated and called as such:
    // NumArray numArray = new NumArray(nums);
    // numArray.sumRange(0, 1);
    // numArray.sumRange(1, 2);```

Log in to reply
 

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