LeetCode_Range Sum Query - Immutable

来源:互联网 发布:淘宝集市c店免费活动 编辑:程序博客网 时间:2024/06/05 17:38

Given an integer array nums, find the sum of the elements between indicesi andj (ij), inclusive.

Example:

Given nums = [-2, 0, 3, -5, 2, -1]sumRange(0, 2) -> 1sumRange(2, 5) -> -1sumRange(0, 5) -> -3

Note:

  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.

解题思路:此题从字面上看并不难,只要找出数组中对应索引位置,并计算从0-index的和并做对应索引的减法即可,但是注意题目中的Note可以发现,你的方法可能会被大量的调用,所以每次调用都去做运算是不合适的,必将出现Time Limited Exceeded。所以需要在类构造时,便需要准备一些结果集(所有索引到0的和),以便在后面的运算中减少计算量。


public class NumArray {private int[] mArr = null;private int[] mResults = null;// 3mspublic NumArray(int[] nums) {mArr = nums;mResults = new int[mArr.length];for (int i = 0; i < mArr.length; i++) {if (i == 0) {mResults[0] = mArr[0];} else {mResults[i] = mResults[i - 1] + mArr[i];}}}public int sumRange(int i, int j) {if (mArr == null || mArr.length - 1 < i || mArr.length - 1 < j || i < 0|| j < 0) {return 0;}int result = i <= 0 ? mResults[j] : (mResults[j] - mResults[i - 1]);return result;}public static void main(String[] args) {int[] nums = { -2, 0, 3, -5, 2, -1 };// sumRange(0, 2) -> 1// sumRange(2, 5) -> -1// sumRange(0, 5) -> -3NumArray numArray = new NumArray(nums);numArray.sumRange(0, 2);numArray.sumRange(2, 5);numArray.sumRange(0, 5);}}

0 0