LeetCode题解:Range Sum Query - Immutable(C++版)
2015-12-10 23:51
531 查看
题目链接:
Range Sum Query - Immutable题目描述:
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
Note:
1.You may assume that the array does not change.
2.There are many calls to sumRange function.
题目解释:
给定一个整型数组,求数组下标[i,j]元素之和,包括元素i和元素j。然后是题目给的例子。
这里要注意题目中提到的两点:
假设数组在整个过程中是不变得。
程序会多次调用sumRange函数。
解题方案:
第一次看到这个题目的时候,我们的第一反应是:从i加到j就可以了呀,但是题目的NOTE里提到:会多次调用sumRange函数,如果采用我们这种方式,时间复杂度就会是O(N*N),这样就会超时。我们的想法是用空间换取时间:使用一个数组存储前k个元素之和,当要求[i,j]元素之和时,我们只要用sum(j)-sum(i-1)即可
当然这里有边界条件需要处理
i = 0时,直接返回sum(j)即可。
给定数组不包含元素时,直接返回0.
下面给出AC代码
class NumArray { public: vector<int> sum; NumArray(vector<int> &nums) { if(nums.size() != 0) { sum.push_back(nums[0]);//将第一个呀 for (int i = 1; i < nums.size(); ++i) { sum.push_back(nums[i]+sum[i-1]); } } //std::cout <<sum[i] << std::endl; } int sumRange(int i, int j) { if(sum.size() == 0) { return 0; } if(i-1 < 0) { return sum[j]; } else { return sum[j] - sum[i-1]; } } }; // Your NumArray object will be instantiated and called as such: // NumArray numArray(nums); // numArray.sumRange(0, 1); // numArray.sumRange(1, 2);
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解