Skip to content

Commit 17df05f

Browse files
committed
Solution for:Num Array
1 parent e2e2802 commit 17df05f

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/leetcode/NumArray.java

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package leetcode;
2+
3+
public class NumArray {
4+
private int[] sums;
5+
public static void main(String[] args) {
6+
NumArray test = new NumArray(new int[]{-2, 0, 3, -5, 2, -1});
7+
System.out.println(test.sumRange(0, 2));
8+
System.out.println(test.sumRange(2, 5));
9+
System.out.println(test.sumRange(0, 5));
10+
11+
}
12+
13+
public NumArray(int[] nums) {
14+
sums = new int[nums.length];
15+
if(nums.length>0)
16+
sums[0]= nums[0];
17+
for(int i=1; i<nums.length; i++)
18+
sums[i] = sums[i-1]+ nums[i];
19+
}
20+
21+
public int sumRange(int i, int j) {
22+
if(i==0) return sums[j];
23+
return sums[j]-sums[i-1];
24+
}
25+
26+
}

0 commit comments

Comments
 (0)