
LeetCode p303 Range Sum Query - Immutable 题解
1.题目:
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
题意:
输出数组某一段的累加和。
2.解题思路:
累加 做差
3.代码
[title] [] [url] [link text]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
public class {
int[] nums;
public (int[] nums) {
for (int i = 1; i < nums.length; i++) { nums[i] += nums[i - 1]; } this.nums = nums; }
public int sumRange(int i, int j) {
if (i == 0) return nums[j]; return nums[j] - nums[i - 1];
} }
|
4.一些总结:
近期评论