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

    动态规划问题

    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.

    个人总结:看到 Note2 应该想到这是一个动态规划问题,每次调用都去计算肯定会超时,因此应该提前把所有结果计算出来。
    此外,一些特殊情况,比如nuns=[],i或者j可能越界,都得考虑到。
    ac代码
    
    public class NumArray{
        
         int[] array,sum;
       public NumArray(int[] nums) {
           if(nums.length==0||nums==null) return;
          array=nums;
          sum=nums;
          sum[0]=array[0];
          for(int i=1;i<array.length;i++){
             sum[i]=sum[i-1]+array[i];
           }
      }
      
      public int sumRange(int i,int j){
          if(sum==null||i>j||j>sum.length) return 0;
          
          else {
               if(i==0)  return sum[j];
               else
              return sum[j]-sum[i-1];     
              }
        }
      }
    
    
    
     
  • 相关阅读:
    Spark介绍与环境搭建
    Kafka基本操作
    Hadoop的HDFS概述
    hadoop环境搭建
    常用小工具
    mac机
    Eclipse使用
    微信公众号开发
    PM2
    JS 零散知识点
  • 原文地址:https://www.cnblogs.com/summer323/p/5026307.html
Copyright © 2011-2022 走看看