LeetCode 303. Range Sum Query

来源:互联网 发布:java 微信支付api 编辑:程序博客网 时间:2024/06/05 16:34

303. Range Sum Query - Immutable

一、问题描述

Given an integer array nums, find the sum of the elements between indices i and j (ij), inclusive.

Note:

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

二、输入输出

Example:

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

三、解题思路

  • 是按照DP TAG来选的题目,结果这道题我实在是看不出来DP的影子。DP是用来解决最优化问题的,这个题完全就没有最优化的影子。如果每次都从i加到j TLE错误。提示里说了会调用方法很多次。
  • 全新的一个思路,只需要o(n)时间复杂度,o(n)的空间复杂度,如果不用sums数组,而是在原来的nums上修改,空间复杂度就成了o(1)
  • 核心思想就是 sum(i, j) = sum(0, j) - sum(0, i-1) 就是把从0到i的和记录下来,之后让求从i到j的和,主要做一次减法就行了,只需要常数时间。
class NumArray {public:        vector<int> sums;        NumArray(vector<int> nums) {            if (nums.empty()) return;            sums.push_back(nums[0]);            for (int i = 1; i < nums.size(); ++i) {                int lastSum = sums[i-1];                sums.push_back(lastSum + nums[i]);            }        }        int sumRange(int i, int j) {            if(i == 0) return sums[j];            return (sums[j] - sums[i-1]);        }};/** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * int param_1 = obj.sumRange(i,j); */
原创粉丝点击