zoukankan      html  css  js  c++  java
  • 303. Range Sum Query

    #week6

    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.

    分析:

    动态规划类型

    状态转移方程:f[i] = f[i-1] + nums[i];

    代码:

    超时版本:

     1 class NumArray {
     2 public:
     3     int** f;
     4     NumArray(vector<int> nums) {
     5         int len = nums.size();
     6         if (len > 0) {
     7         f = new int* [len];
     8         for (int i = 0; i < len; i++) f[i] = new int[len];
     9         f[0][0] = nums[0];
    10         for (int i = 0; i < len; i++)
    11             for (int j = i; j < len; j++) {
    12                 if (i == j) f[i][j] = nums[i];
    13                 else {
    14                     f[i][j] = f[i][j-1] + nums[j];
    15                 }
    16             }
    17         } else {
    18             f = new int*[1];
    19             f[0] = new int[1];
    20             f[0][0] = 0;
    21         }
    22     }
    23     
    24     int sumRange(int i, int j) {
    25         return f[i][j];
    26     }
    27 };
    28 
    29 /**
    30  * Your NumArray object will be instantiated and called as such:
    31  * NumArray obj = new NumArray(nums);
    32  * int param_1 = obj.sumRange(i,j);
    33  */

    修改为一维,不超时:

     1 class NumArray {
     2 public:
     3     int* f;
     4     NumArray(vector<int> nums) {
     5         int len = nums.size();
     6         if (len > 0) {
     7             f = new int [len];
     8             f[0] = nums[0];
     9             for (int i = 1; i < len; i++)
    10                 f[i] = f[i-1] + nums[i];
    11         } else {
    12             f = new int[1];
    13             f[0] = 0;
    14         }
    15     }
    16     
    17     int sumRange(int i, int j) {
    18         return f[j] - f[i-1];
    19     }
    20 };
    21 
    22 /**
    23  * Your NumArray object will be instantiated and called as such:
    24  * NumArray obj = new NumArray(nums);
    25  * int param_1 = obj.sumRange(i,j);
    26  */
  • 相关阅读:
    微信开发-微信红包实例;
    微信支付-商户调用支付接口失败,已完成交易接口升级的用户应使用新接口进行交易;
    JS 获取当前时间
    微信支付-退款之CURL 52
    Binniabia is what?
    WIN7 自动同步服务器上备份文件
    WIN7 自动同步服务器上备份文件
    CSS之clearfix清除浮动
    解决IOS iframe不滚动问题
    CSS文字不换行,溢出省略
  • 原文地址:https://www.cnblogs.com/iamxiaoyubei/p/8278221.html
Copyright © 2011-2022 走看看