303. Range Sum Query - Immutable
2016-01-26 20:46
295 查看
303. Range Sum Query - Immutable
Difficulty: Easy
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.
给定一个整数序列,求指定子序列和。
提示:数组不会发生变化;大量sumRange函数调用。
题目本身非常简单,只需要遍历 i 到 j ,累计得到和即可。但是,这样是TLE(time limit exceeded)的,所给提示也就没有意义了。
所以,题目考察的是效能,换一个方向思考,我们可以存储前i个元素的和;
那么[i,j]子序列和 =sum[j]−sum[i−1];
注意,i==0时,直接返回sum[j]即可。
要点:
1,结构体指针需要初始化,
2,结构体指针的成员指针同样需要初始化,
Difficulty: Easy
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.
给定一个整数序列,求指定子序列和。
提示:数组不会发生变化;大量sumRange函数调用。
题目本身非常简单,只需要遍历 i 到 j ,累计得到和即可。但是,这样是TLE(time limit exceeded)的,所给提示也就没有意义了。
所以,题目考察的是效能,换一个方向思考,我们可以存储前i个元素的和;
那么[i,j]子序列和 =sum[j]−sum[i−1];
注意,i==0时,直接返回sum[j]即可。
struct NumArray { int* a; int* sum; int len; }; /** Initialize your data structure here. */ struct NumArray* NumArrayCreate(int* nums, int numsSize) { int i,temp; struct NumArray* numarray; numarray=(struct NumArray*)malloc(sizeof(struct NumArray)); numarray->a=nums; numarray->len=numsSize; numarray->sum=(int*)malloc(numarray->len*sizeof(int)); temp=0; for(i=0;i<numsSize;i++) //记录前i个值之和 { temp+=numarray->a[i]; numarray->sum[i]=temp; } return numarray; } int sumRange(struct NumArray* numArray, int i, int j) { if(i==0) //若i=0直接为前j个值之和 return numArray->sum[j]; else //若i>0则前j个值之和减去前i-1个值之和即为i到j的值之和 return numArray->sum[j]-numArray->sum[i-1]; } /** Deallocates memory previously allocated for the data structure. */ void NumArrayFree(struct NumArray* numArray) { free(numArray->sum); free(numArray); } // Your NumArray object will be instantiated and called as such: // struct NumArray* numArray = NumArrayCreate(nums, numsSize); // sumRange(numArray, 0, 1); // sumRange(numArray, 1, 2); // (numArray);
要点:
1,结构体指针需要初始化,
struct NumArray* numarray=(struct NumArray*)malloc (sizeof(struct NumArray));
2,结构体指针的成员指针同样需要初始化,
numarray->sum=(int*)malloc(numarray->len*sizeof(int));
相关文章推荐
- UIAlertController的使用——创建提示窗口
- iOS主线程更新UI
- UI父视图子视图加载
- Packet for query is too large
- Dynamic Web Module 3.0 requires Java 1.6 or newer
- MR-2.输入格式(InputFormat)TextInputFormat和SequenceFileInputFormat源码分析
- android 不能在子线程中更新ui的讨论和分析
- UE4 main classes explanation
- UI_UIImageView 基本操作
- zoj 3911 Prime Query 第一发线段树
- LeetCode Question Difficulty Distribution
- 【转】android UI进阶之自定义组合控件
- JS ueditor编辑器
- phpQuery采集乱码问题解决方案
- 二:UIKit与Quartz 2D绘图技术学习
- 整合UEditor,SSH下
- not-null property references a null or transient value:
- X-Requested-With
- 下拉刷新时UITableView的section headerView冲突的解决
- 设备管理,连接两个数据库,用的easygui