303. Range Sum Query - Immutable (Easy)
https://leetcode.com/problems/range-sum-query-immutable/
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
Example:
Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3
Note:
- You may assume that the array does not change.
- There are many calls to sumRange function.
Solutions
class NumArray {
private int[] nums;
private int[] sums;
private boolean valid = true;
public NumArray(int[] nums) {
// verify the validness of given array
if (nums == null || nums.length == 0) {
valid = false;
return;
}
this.nums = nums;
sums = new int[nums.length];
sums[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
sums[i] = sums[i-1] + nums[i];
}
}
public int sumRange(int i, int j) {
if (!valid) {
return 0;
}
return sums[j] - sums[i] + nums[i];
}
}
Incorrect Solutions
class NumArray {
private int[] nums;
private int[] sums;
public NumArray(int[] nums) {
this.nums = nums;
sums = new int[nums.length];
sums[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
sums[i] = sums[i-1] + nums[i];
}
}
public int sumRange(int i, int j) {
return sums[j] - sums[i] + nums[i];
}
}