看到leetcode这个网站,这个网站上的题都是一些经典的公司用来面试应聘者的面试题,感觉不错,就挑个最简单的题目来做:Range Sum Query
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.
题目的意思就是求数组中指定区间的和,并且求和函数会调用很多次。
直接Python写:
class NumArray(object): def __init__(self, nums): """ initialize your data structure here. :type nums: List[int] """ self.num = nums def sumRange(self, i, j): """ sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int """ reduce(lambda x,y:x+y,self.num[i:j+1]) if __name__ == '__main__': nums = [-2, 0, 3, -5, 2, -1] print sum(nums) numArray = NumArray(nums) numArray.sumRange(0, 1) numArray.sumRange(1, 2)
嗯,个人感觉挺简洁,运行后也没错误,复制代码提交,结果提示超时了~~~,再改代码
class NumArray(object): def __init__(self, nums): """ initialize your data structure here. :type nums: List[int] """ self.num = nums def sumRange(self, i, j): """ sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int """ sum(self.num[i:j+1])
这回应该没问题了吧,提交后还是提示超时,崩溃!上网查,网上都有答案了,因为sumRange函数要调用多次,所以不能每次调用都要计算,应该在初始化时计算好。。。唉,怎么没想到呢,改代码
class NumArray(object): def __init__(self, nums): """ initialize your data structure here. :type nums: List[int] """ self.sum = [0] for item in nums: self.sum.append(self.sum[-1]+item) def sumRange(self, i, j): """ sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int """ return self.sum[j + 1] - self.sum[i]
OK,成功!!!
附C++代码:
#include <stdio.h> #include <vector> using namespace std; class NumArray { public: vector <int> Mynum; NumArray(vector<int> &nums) { Mynum.push_back(0); vector<int>::iterator it; for(it=nums.begin();it!=nums.end();it++) { Mynum.push_back(Mynum.back()+ *it); } } int sumRange(int i, int j) { return Mynum[j+1]-Mynum[i]; } }; int main() { vector <int> nums; nums.push_back(-2); nums.push_back(0); nums.push_back(3); nums.push_back(-5); nums.push_back(2); nums.push_back(-1); NumArray numArray(nums); printf("%d\n",numArray.sumRange(0, 1)); printf("%d\n",numArray.sumRange(1, 2)); return 0; }
顺利通过。思路很重要!!!思路很重要!!!思路很重要!!!
浙公网安备 33010602011771号