• leetcode 303. 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.

    题目大意:给定一个数组,返回小标[i, j]的元素之和。

    用途:在窗口一定大小时,做滑动平均。可用于图像中的均值滤波

    思路一:每次给定[i, j],直接计算。

     1 class NumArray {
     2 private:
     3     vector<int> sum;
     4 public:
     5     NumArray(vector<int>& nums) {
     6         sum = nums;
     7     }
     8     
     9     int sumRange(int i, int j) {
    10         int ans = 0;
    11         for (int k = i; k <= j; ++k) {
    12             ans += sum[k];
    13         }
    14         return ans;
    15     }
    16 };

    思路二:

    sum[k] 记录 [0,k]的累加和,计算下标[i, j]的元素和为sum[j] - sum[i - 1], k = 0时,sum[0] = nums[0];

     1 class NumArray {
     2 private:
     3     vector<int> sum;
     4 public:
     5     NumArray(vector<int>& nums) {
     6         sum.assign(nums.begin(), nums.end());
     7         for (int i = 1; i < nums.size(); ++i) {
     8             sum[i] = sum[i - 1] + nums[i];
     9         }
    10     }
    11     
    12     int sumRange(int i, int j) {
    13         if (i == 0) return sum[j];
    14         return sum[j] - sum[i - 1];
    15     }
    16 };

     python3:

     1 class NumArray:
     2     def __init__(self, nums: List[int]):
     3         self.lists = [] #定义实例变量
     4         for i, v in enumerate(nums):
     5             if i == 0:
     6                 self.lists.append(v)
     7             else:
     8                 self.lists.append(self.lists[-1] + v)
     9 
    10     def sumRange(self, i: int, j: int) -> int:
    11         if i == 0:
    12             return self.lists[j]
    13         return self.lists[j] - self.lists[i - 1]

    class NumArray:    def __init__(self, nums: List[int]):        self.lists = []        for i, v in enumerate(nums):            if i == 0:                self.lists.append(v)            else:                self.lists.append(self.lists[i-1] + v)
        def sumRange(self, i: int, j: int) -> int:        if i == 0:            return self.lists[j]        return self.lists[j] - self.lists[i - 1]

  • 相关阅读:
    编写一个最原始的Servlet
    windows 通过cmd使用tail命令
    windows 配置jdk8环境变量
    Windows tomcat简单使用
    红黑树
    HashMap源码分析--jdk1.7
    IDEA debug断点调试技巧--转载
    idea 调试的时候变量的值变成了jar包显示
    浅谈Java中的hashcode方法--转载
    家庭记账本之微信小程序(八)
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/12160087.html
Copyright © 2020-2023  润新知