Leetcode 303 Range Sum Query

来源:互联网 发布:啊哈 算法 epub 编辑:程序博客网 时间:2024/06/05 16:21

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) -> 1sumRange(2, 5) -> -1sumRange(0, 5) -> -3

Note:

  1. You may assume that the array does not change.

  1. There are many calls to sumRange function.
基本方法可以做,但是time 超了= 。=
考虑在复制的时候进行累加和计算。
public class NumArray {       int[] array;public NumArray(int[] nums) {    for(int i = 1; i < nums.length; i++)        nums[i] += nums[i - 1];        array = nums;}public int sumRange(int i, int j) {    if(i == 0)        return array[j];        return array[j] - array[i - 1];}}/** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * int param_1 = obj.sumRange(i,j); */


原创粉丝点击