LeetCode题解:Range Sum Query - Immutable(C++版本)
2015-11-22 10:44
441 查看
题目链接:
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 之间的元素之和,包括nums[i]和nums[j]这两个首尾元素。具体实例看上文,这里还要注意最后两句的note,提到:假定数组在程序执行过程中不会变,我们的代码会多次调用sumRange()函数。解题方案:
看到这个题目描述,我们第一个反应就是,将数组从nums[i]一直加到nums[j]就可以了呀,时间复杂度为O(n),很不错了呢,可是上文提到一点:我们的代码会多次调用sumRange()函数, 多次调用以后我们的时间复杂度就变为O(n*n)了。所以这样的方案是不可行的。像这样子我们只能使用空间换取时间了:我们使用一个数字记录下前K个元素之和,当我们求i j之间元素之和时,之间用前j之和减掉前i-1之和即可 ,这样在单次求和的过程中的复杂度为O(1),整体复杂度为O(n) + O(n),这样我们就AC了
———下面看AC的C++代码
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 题解