303. Range Sum Query - Immutable

Posted wentiliangkaihua

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了303. 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:

You may assume that the array does not change.

There are many calls to sumRange function.

  1. class NumArray {
        private final int[] arr;
    
        public NumArray(int[] nums) {
            this.arr = new int[nums.length];
            int sum = 0;
            for(int i = 0; i < nums.length; i++){
                sum += nums[i];
                arr[i] = sum;
            }
        }
        
        public int sumRange(int i, int j) {
            return arr[j] - (i == 0 ? 0 : arr[i - 1]);
        }
    }

    arr[i]是nums数组从0到i(包括)的sum,所以要求i,j之间的和,先判断i是否为0,然后等于arr[j] - arr[i - 1]。

以上是dp解法。

??倒是觉得easy题就要有easy题的亚子,直接设一个数组复制不就完了吗.

class NumArray {
    private final int[] arr;

    public NumArray(int[] nums) {
        arr = nums.clone();
    }
    
    public int sumRange(int i, int j) {
        int res = 0;
        for(int m = i; i <= j; i++){
            res += arr[i];
        }
        return res;
    }
}

 

以上是关于303. Range Sum Query - Immutable的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode-303 Range Sum Query - Immutable

303. Range Sum Query - Immutable

303. Range Sum Query - Immutable

303. Range Sum Query - Immutable

303. Range Sum Query - Immutable

LeetCode 303. Range Sum Query - Immutable