Problem: 303. 区域和检索 - 数组不可变
文章目录
- 题目描述
- 思路
- 复杂度
- Code
题目描述
思路
创建前缀和数组preSum,其中preSum[i]处元素值为nums[0] - nums[i - 1]处元素值得和,当调用sumRange函数时直接返回preSum[right + 1] - preSum[left]
复杂度
函数sumRange的时间空间复杂度
时间复杂度:
O ( 1 ) O(1) O(1)
空间复杂度:
O ( 1 ) O(1) O(1)
Code
class NumArray {// Prefix arrayprivate int[] preSum;/*** Construct prefix sum** @param nums Given array*/public NumArray(int[] nums) {preSum = new int[nums.length + 1];for (int i = 1; i < preSum.length; ++i) {preSum[i] = preSum[i - 1] + nums[i - 1];}}/*** Query the sum of the closed interval [left, right]** @param left Left boundary* @param right Right boundary* @return int*/public int sumRange(int left, int right) {return preSum[right + 1] - preSum[left];}
}/*** Your NumArray object will be instantiated and called as such:* NumArray obj = new NumArray(nums);* int param_1 = obj.sumRange(left,right);*/