作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/range-sum-query-immutable/description/

题目描述

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.

解题方法

保存累积和

可以直接用切片求和的方法做,也能A,但是效率太慢。

下面这个方式可以先把sums求出来,然后再调用的时候直接右边的sums-左边的sums即可得到结果。

class NumArray(object):

    def __init__(self, nums):
"""
:type nums: List[int]
"""
self.sums = [0] * len(nums)
total = 0
for i, num in enumerate(nums):
total += num
self.sums[i] = total def sumRange(self, i, j):
"""
:type i: int
:type j: int
:rtype: int
"""
if i == 0:
return self.sums[j]
else:
return self.sums[j] - self.sums[i - 1] # Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)

如果多用一个元素放在开头,那么上面的这个代码可以简化。

class NumArray(object):

    def __init__(self, nums):
"""
:type nums: List[int]
"""
N = len(nums)
self.sums = [0] * (N + 1)
for i in range(1, N + 1):
self.sums[i] = self.sums[i - 1] + nums[i - 1] def sumRange(self, i, j):
"""
:type i: int
:type j: int
:rtype: int
"""
return self.sums[j + 1] - self.sums[i] # Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)

日期

2018 年 2 月 4 日
2018 年 11 月 24 日 —— 周六快乐

最新文章

  1. ORACLE分区表梳理系列(二)- 分区表日常维护及注意事项(红字需要留意)
  2. python 输出大文本文件
  3. nginx root和alias指令的区别
  4. 二、freemarker.controller半自动静态化+Tomcat虚拟资源映射
  5. Linux卸载系统自带的httpd的方法
  6. swift 创建tableView 并实现协议
  7. CodeForces 625D Finals in arithmetic
  8. linux命令----查看磁盘空间
  9. pinyin.js
  10. Python3入门机器学习经典算法与应用
  11. MRPT 安装使用
  12. [原]Jenkins(三)---Jenkins初始配置和插件配置
  13. Apache升级PHP教程(以5.3.3升级到5.6.30为例)
  14. 3.window窗口
  15. mount 需要同时设置 noatime 和 nodiratime 吗?
  16. string的七种用法
  17. Atitit . 编程模型的变革总结
  18. python 写文件write(string), writelines(list) ,读文件
  19. 一个表中的字段值用作另一个表的In查询条件
  20. Ansible 删除多个文件或目录

热门文章

  1. 56-Remove Linked List Elements
  2. Git五个常见问题及解决方法
  3. C语言之内核中的struct list_head 结构体
  4. 学习java的第九天
  5. A Child's History of England.34
  6. 一起手写吧!ES5和ES6的继承机制!
  7. C++基本函数的调用优化(构造、拷贝构造、赋值)
  8. Spring整合Ibatis之SqlMapClientDaoSupport
  9. mysqldump备份容灾脚本
  10. MVCC详解