本文主要是介绍LeetCode *** 303. 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.
代码:
class NumArray {
public:int *num;NumArray(vector<int> &nums) {int size=nums.size();num=new int[size+1];num[0]=0;for(int i=0;i<size;++i)num[i+1]=num[i]+nums[i];}int sumRange(int i, int j) {if(i==0)return num[j+1];return num[j+1]-num[i];}
};// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
这篇关于LeetCode *** 303. Range Sum Query - Immutable的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!