Range Sum Query - Immutable
2015-12-22 11:26
393 查看
Given an integer array nums, find the sum of the elements between indices
i and j (i ≤ j), inclusive.
Example:
Note:
You may assume that the array does not change.
There are many calls to sumRange function.
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.
public class ThreadTest{//求给定数组的[i,j]闭区间之内的元素的和 public static void main(String args[]){ int[] a={1,2,3,4,5}; sums(a); System.out.println(sumsRange(3,4)); } public static int [] sums;//这个里边的成员变量和成员函数貌似都必须定义为public static,不然不能用,具体不太懂 public static void sums(int[] nums){//定义了一个求数组nums和的数组sums if(nums==null) sums=null; else if(nums.length==0) sums=new int[0]; else{ sums=new int[nums.length]; sums[0]=nums[0]; for(int i=1;i<nums.length;i++){ sums[i]=sums[i-1]+nums[i]; } } } public static int sumsRange(int i,int j){//用上边的求和数组的差来求 if(sums==null)//这儿的判断依据是数组sums而不是nums return 0; if(i>j||i>sums.length||j<0) return 0; else if (i==0) return sums[j]; else return sums[j]-sums[i-1]; } }
相关文章推荐
- 单击双击手势(UITapGestureRecognizer)
- echarts折线图纵横轴采用类似定义{value}KB/s单位过长被遮挡
- Arduino - 蓝牙串口透传模块:HC-06从机
- OC-UI-005.transform属性,用于平移,放大,旋转
- UIAlertController使用方法、UIAlertAction使用方法(8.0起新控件)
- Leetcode: Verify Preorder Sequence in Binary Search Tree
- Word Pattern pattern = "abba", str = "dog cat cat dog" should return true
- OC-UI-004.纯代码编写按钮的简单方法
- OC-UI-003.开始简单的动画效果,2种方式
- UIView block动画
- AddComponentMenu ContextMenu ExecuteInEditMode HideInInspector NonSerialized RPC RequireComponent Se
- OC-UI-002.按钮的属性frame、bounds、center
- xib中UIView设置圆角
- (二)hue与HDFS、YARN集成配置与测试
- ActionContext、ValueStack、Stack Context之间的关系
- UIControl 纠错
- iOS UISearchController的使用
- Maya Mel GUI入门
- NSValue可以将结构转化为对象,并把它存储在集合中。
- 【译】UI设计基础(UI Design Basics)--启动与停止(Starting and Stopping)(五)