zoukankan      html  css  js  c++  java
  • leetcode range sum query

    Given an integer array nums, find the sum of the elements between indices i and j (ij), 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.

    刚开始看题,有些不懂,暴力破解后time exceed。很简单,聪明的人大概一会儿就想出来了。

     1 class NumArray {
     2     vector<int> sumArray;
     3 public:
     4     NumArray(vector<int> &nums) {
     5 
     6         int temp=0;
     7         for(int i=0;i<nums.size();i++){
     8             temp+=nums[i];
     9             sumArray.push_back(temp);
    10         }
    11     }
    12 
    13     int sumRange(int i, int j) {
    14         int result;
    15         result=this->sumArray[j]-this->sumArray[i-1];
    16         return result;
    17     }
    18 };
    19 
    20 
    21 // Your NumArray object will be instantiated and called as such:
    22 // NumArray numArray(nums);
    23 // numArray.sumRange(0, 1);
    24 // numArray.sumRange(1, 2);

    题外话:

    最近状态有些不好,我事实上是一个常常状态不好的人,我【容易受环境干扰】、【理性感性参半】、【不容易坚守自己】

    因为上述的缺点,常常陷入责怪自己的状态中,却不知道如何改变,最差却一直使用的解决办法就是明天再说,也许明天就好了。呸。

  • 相关阅读:
    MySQL
    MySQL
    MySQL
    javaScript之深度理解原型链
    javaScript之this的五种情况
    ES6之箭头函数中的this
    javaScript之跨浏览器的事件对象
    javaScript之事件处理程序
    javaScript之promise
    VUE之使用百度地图API
  • 原文地址:https://www.cnblogs.com/LUO77/p/4956093.html
Copyright © 2011-2022 走看看