LeetCode -- Range Sum Query
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode -- Range Sum Query相关的知识,希望对你有一定的参考价值。
geQuestion:
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.
Analysis:
给出一个整数数组,得出i与j之间的数字之和(i<=j)。你可以假设数组不会改变,并且他们可以调用多次sunRange函数。
Answer:
public class NumArray { int[] num; public NumArray(int[] nums) { this.num = nums; } public int sumRange(int i, int j) { int res = 0; for(int k=i; k<j+1; k++) { res += num[k]; } return res; } } // Your NumArray object will be instantiated and called as such: // NumArray numArray = new NumArray(nums); // numArray.sumRange(0, 1); // numArray.sumRange(1, 2);
以上是关于LeetCode -- Range Sum Query的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 303. Range Sum Query - Immutable
leetcode笔记:Range Sum Query 2D - Immutable
leetcode@ [327] Count of Range Sum (Binary Search)