本文主要是介绍[LeetCode] 303. Range Sum Query - Immutable,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题:https://leetcode.com/problems/range-sum-query-immutable/description/
题目
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.
题目大意
实现方法,求区间 i ~ j 的和,i、j包含。
解题思路
求区间 i ~ j 的和,可以转换为 sum[j + 1] - sum[i],其中 sum[i] 为 0 ~ i - 1 的和。
求解sum[j] = sum[j-1] + nums[j-1]
class NumArray {int[] sums;public NumArray(int[] nums) {sums = new int[nums.length+1];sums[0] = 0;for(int i = 1;i<=nums.length;i++){sums[i] = sums[i-1] + nums[i-1];}}public int sumRange(int i, int j) {return sums[j+1] - sums[i];}
}/*** Your NumArray object will be instantiated and called as such:* NumArray obj = new NumArray(nums);* int param_1 = obj.sumRange(i,j);*/
这篇关于[LeetCode] 303. Range Sum Query - Immutable的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!