Range Sum Query - Immutable

来源:互联网 发布:知乎年薪百万是什么梗 编辑:程序博客网 时间:2024/05/16 10:43

题目地址:https://leetcode.com/problems/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:

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

一般想法:

public class NumArray {    private int[] nums;    public NumArray(int[] nums) {        this.nums = nums;    }    public int sumRange(int i, int j) {        int sum = 0;        if (i <= 0)            i = 0;        if (j > nums.length - 1)            j = nums.length - 1;        for (int k = i; k <= j; k++)             sum += nums[k];        return sum;    }}

这么搞可能会超时,所以为了避免超时,我们可以先把首元素到每个元素的和先算出来,并保存下来,代码如下:

public class NumArray {    private int[] sums;    public NumArray(int[] nums) {        int sum = 0;        this.sums = new int[nums.length];        for (int i = 0; i < nums.length; i++) {            sum += nums[i];            sums[i] = sum;        }    }    public int sumRange(int i, int j) {        if (i == 0)            return sums[j];        return sums[j] - sums[i - 1];    }    public static void main(String[] args) {        int[] nums = {-2, 0, 3, -5, 2, -1};        NumArray numArray = new NumArray(nums);        System.out.println(numArray.sumRange(2, 5));    }}

这样就不会超时了。

0 0
原创粉丝点击