Skip to content

Commit 7df64b1

Browse files
author
王俊超
committed
commit
1 parent f68ebb6 commit 7df64b1

File tree

3 files changed

+47
-0
lines changed

3 files changed

+47
-0
lines changed

Diff for: .idea/modules.xml

+1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* @author: wangjunchao(王俊超)
3+
* @time: 2018-10-12 13:53
4+
**/
5+
public class NumArray {
6+
private int[] nums;
7+
8+
public NumArray(int[] nums) {
9+
this.nums = nums;
10+
}
11+
12+
public int sumRange(int i, int j) {
13+
14+
if (i > j) {
15+
throw new IllegalArgumentException("i = " + i + ", j = " + j +", i must not greater than j");
16+
}
17+
18+
if (j < 0) {
19+
throw new IllegalArgumentException("i = " + i + ", j = " + j +", i must not less than 0");
20+
}
21+
22+
i = i < 0 ? 0 : i;
23+
j = j >= nums.length ? nums.length - 1 : j;
24+
25+
int sum = 0;
26+
27+
28+
for (int k = i; k <= j; k++) {
29+
sum += nums[k];
30+
}
31+
32+
return sum;
33+
}
34+
}
+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
/**
2+
* @author: wangjunchao(王俊超)
3+
* @time: 2018-10-12 14:17
4+
**/
5+
public class Test {
6+
public static void main(String[] args) {
7+
NumArray array = new NumArray(new int[]{-2, 0, 3, -5, 2, -1});
8+
System.out.println(array.sumRange(0, 2));
9+
System.out.println(array.sumRange(2, 5));
10+
System.out.println(array.sumRange(0, 5));
11+
}
12+
}

0 commit comments

Comments
 (0)