LeetCode -- Range Sum Query - Immutable
来源:互联网 发布:古龙顺序知乎 编辑:程序博客网 时间:2024/05/16 14:05
LeetCode -- Range Sum Query - Immutable
题目描述
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:
You may assume that the array does not change.
There are many calls to sumRange function.
传入起始索引,返回数组求和的值。
思路:
使用缓存前n项的和。
题目描述
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:
You may assume that the array does not change.
There are many calls to sumRange function.
传入起始索引,返回数组求和的值。
思路:
使用缓存前n项的和。
public class NumArray { private int[] _cacheSum ;private int[] _nums; public NumArray(int[] nums) {_nums = nums;_cacheSum = new int[nums.Length]; var s = 0; for (var i = 0;i < nums.Length; i++){ s += nums[i]; _cacheSum[i] = s; } } public int SumRange(int i, int j) { if(_nums == null || _nums.Length == 0){return 0;}if(i < 0 || j > _nums.Length - 1){return 0;}return _cacheSum[j] - _cacheSum[i] + _nums[i]; }}
1 0
- [LeetCode] Range Sum Query - Immutable
- [LeetCode]Range Sum Query - Immutable
- LeetCode Range Sum Query - Immutable
- LeetCode Range Sum Query - Immutable
- LeetCode:Range Sum Query - Immutable
- [Leetcode]Range Sum Query - Immutable
- leetcode Range Sum Query - Immutable
- leetcode- Range Sum Query - Immutable
- leetcode:Range Sum Query - Immutable
- Leetcode: Range Sum Query - Immutable
- Leetcode: Range Sum Query - Immutable
- 【leetcode】:Range Sum Query - Immutable
- leetcode--Range Sum Query - Immutable
- LeetCode Range Sum Query - Immutable
- LeetCode|Range Sum Query - Immutable
- LeetCode:Range Sum Query - Immutable
- 【Leetcode】Range Sum Query - Immutable
- LeetCode -- Range Sum Query - Immutable
- 单例模式(从放弃到入门)
- gdb调试器
- C关键字 register extern const static volatile typedef 逐一浅析
- jQuery中$.get、$.post、$.getJSON和$.ajax的用法详解
- Python-pip下载超时问题
- LeetCode -- Range Sum Query - Immutable
- jenkins+tomcat配置(初学,有错误,还请指正)
- Hibernate中使用 Serializable id
- Python selenium 三种等待方式详解(必会)
- python SQLite3 插入数据问题
- usaco Combination Lock
- 换硬币问题
- python学习笔记 filter和sorted
- 数据库(3):MySQL优化GROUP BY-松散索引扫描与紧凑索引扫描