[C#]LeetCode303. 区域和检索 - 数组不可变 | Range Sum Query - Immutable
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了[C#]LeetCode303. 区域和检索 - 数组不可变 | Range Sum Query - Immutable,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2302字,纯文字阅读大概需要4分钟。
内容图文
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.
给定一个整数数组 nums,求出数组从索引 i 到 j (i ≤ j) 范围内元素的总和,包含 i, j 两点。
示例:
给定 nums = [-2, 0, 3, -5, 2, -1],求和函数为 sumRange() sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3
说明:
- 你可以假设数组不可变。
- 会多次调用 sumRange 方法。
452ms
1 public class NumArray { 2 3 int[] res; 4 public NumArray(int[] nums) { 5 res = new int[nums.Length + 1]; 6 7 for (int i = 0 ; i < nums.Length; i++) 8 { 9 res[i+1] += res[i] + nums[i]; 10 } 11 } 12 13 public int SumRange(int i, int j) { 14 15 return res[j+1] - res[i]; 16 } 17 } 18 19 /** 20 * Your NumArray object will be instantiated and called as such: 21 * NumArray obj = new NumArray(nums); 22 * int param_1 = obj.SumRange(i,j); 23 */
456ms
1 public class NumArray { 2 List<int> sumList = new List<int>(); 3 int[] x; 4 public NumArray(int[] nums) { 5 int res = 0; 6 sumList.Add(res); 7 for(int i = 0; i < nums.Length; ++i) 8 { 9 res += nums[i]; 10 sumList.Add(res); 11 } 12 x = nums; 13 } 14 15 public int SumRange(int i, int j) { 16 if(i == j) 17 return x[i]; 18 return sumList[j+1] - sumList[i]; 19 } 20 } 21 22 /** 23 * Your NumArray object will be instantiated and called as such: 24 * NumArray obj = new NumArray(nums); 25 * int param_1 = obj.SumRange(i,j); 26 */
476ms
1 public class NumArray { 2 List<int> sumList = new List<int>(); 3 public NumArray(int[] nums) { 4 int res = 0; 5 sumList.Add(res); 6 for(int i = 0; i < nums.Length; ++i) 7 { 8 res += nums[i]; 9 sumList.Add(res); 10 } 11 } 12 13 public int SumRange(int i, int j) { 14 return sumList[j+1] - sumList[i]; 15 } 16 } 17 18 /** 19 * Your NumArray object will be instantiated and called as such: 20 * NumArray obj = new NumArray(nums); 21 * int param_1 = obj.SumRange(i,j); 22 */
内容总结
以上是互联网集市为您收集整理的[C#]LeetCode303. 区域和检索 - 数组不可变 | Range Sum Query - Immutable全部内容,希望文章能够帮你解决[C#]LeetCode303. 区域和检索 - 数组不可变 | Range Sum Query - Immutable所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。