[Leetcode] Range Sum Query - Immutable
来源:互联网 发布:kali扫描sql注入点 编辑:程序博客网 时间:2024/05/22 02:28
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) -> 1sumRange(2, 5) -> -1sumRange(0, 5) -> -3
Note:
- You may assume that the array does not change.
- There are many calls to sumRange function.
题目很清晰,求整型数组从i至j的元素值和,很容易想到循环求解,这里用链表方式实现了:
struct NumArray { int val; struct NumArray *next;};/** Initialize your data structure here. */struct NumArray* NumArrayCreate(int* nums, int numsSize) {struct NumArray *head = NULL, *tmpNext = NULL;int i = 0;if(!nums || numsSize <= 0)return NULL;while(numsSize --){struct NumArray *tmp = malloc(sizeof(struct NumArray));if(tmp == NULL){return NULL;}tmp->val = nums[i++];tmp->next = NULL;if(head == NULL){head = tmp;tmpNext = head;continue;}else{tmpNext->next = tmp;tmpNext = tmp;}}return head; }int sumRange(struct NumArray* numArray, int i, int j) { if(NULL == numArray || i > j) { return 0; } int dist = j - i + 1; int sum = 0; struct NumArray *p = numArray; while(i) { if(p->next){p = p->next;} i --; } while(dist) { if(p){ sum += p->val; p = p->next; } else{ break; } dist -= 1; } return sum;}/** Deallocates memory previously allocated for the data structure. */void NumArrayFree(struct NumArray* numArray) {struct NumArray*p = numArray; while(p) { struct NumArray *tmp = p->next; free(p); p = tmp; }}
刚开始一直觉得这个题是不是太简单了,看了提示才知道这是要考查执行效率,试想这种求和要执行一万次,时间
会是多久?能否将时间尽量缩短?从答案给出的结果来看采用预先计算出从第一个元素到当前元素所有元素的和,保存下来,在函数sumRange中就可以很方便地不需要另外的循环计算该和了,这种使用“缓存(Cache)”的方式值得深思,尤其在日常工作中写代码要考虑好这一点是否可以沿用,给出答案以作日后参考。
private int[] sum;public NumArray(int[] nums) { sum = new int[nums.length + 1]; for (int i = 0; i < nums.length; i++) { sum[i + 1] = sum[i] + nums[i]; }}public int sumRange(int i, int j) { return sum[j + 1] - sum[i];}
0 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
- 博为峰Java技术题 ——JavaEE Servlet 国际化Ⅲ
- pdo exec()函数实现insert update操作
- 单帧旋转动画
- 阿里云centos6.5安装MySQL5.5
- 支付密码页面
- [Leetcode] Range Sum Query - Immutable
- Deep Learning in NLP (一)词向量和语言模型
- 线程之间的通信
- Objective-C 枚举的使用
- 树莓派的libpacp的使用分析
- 页面显示实时数据
- java关键字之native
- 掌握的几种禁止转换八进制,十进制,十六禁止
- 对一个8bit unsigned char的数据的指定位进行置1或置0操作,其它位保持不变