leetcode--Range Sum Query - Immutable
2016-03-08 11:59
357 查看
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:
解:
想了半天怎么动态规划(打表)将sumRange在初始化的时候存到一个二元数组,怎么想都是O( n2)n^2)
其实有可以O(n)初始化O(1)查询的解法
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.
解:
想了半天怎么动态规划(打表)将sumRange在初始化的时候存到一个二元数组,怎么想都是O( n2)n^2)
其实有可以O(n)初始化O(1)查询的解法
int[] nums; public NumArray(int[] nums) { for(int i = 1; i < nums.length; i++) nums[i] += nums[i - 1]; this.nums = nums; } public int sumRange(int i, int j) { if(i == 0) return nums[j]; return nums[j] - nums[i - 1]; }
相关文章推荐
- android开发系列之由ContentValues看到的
- 子线程更新UI,牵扯activity的启动过程
- JEasyUI: Create endless progressbar
- UMEditor(Ueditor mini)修改图片上传路径
- //改变UITextfield的Placeholder字体的颜色
- 详解 CALayer 和 UIView 的区别和联系
- No matching provisioning profile found: Your build settings specify a provis...
- 解决The current branch is not configured for pull No value for key branch.master.merge found in confi
- [iOS]关于UILabel显示多颜色字体的问题
- 百度编辑器-Ueditor
- 对Viewcontroller在UINavigationController中入栈出栈的一点点理解
- bluez 协议栈实现3 应用层的协议栈实现分析之dbus
- Fragment UI显示重叠问题
- ERROR:invalid byte sequence for encoding"UTF8"
- 解决CE6和CE5在Platform Builder的Connectivity Options上的冲突
- git pull request工作模式
- Storyboard中的UIScrollView使用自动布局,使其能够滚动
- GPUImage遇到的坑
- Qt使用教程之使用Qt Quick UI表单(五)
- iOS 疑难杂症(什么鬼系列)— — UIButton 点击卡顿/延迟