Leetcode
easy
design
prefix sum
array
python
c++
Learn More →
Learn More →
此題為設計實做一個NumArray類別,使用sumRange(i, j) 時要能夠回傳[i, j]範圍內的和
prefix sum前綴和想法
ex: nums =[-2, 0, 3, -5, 2, -1]
self.nums =[-2, 0, 3, -5, 2, -1]
self.sumArray=[-2,-2, 1, -4,-2, -3]
sumRange(2,5)= (-3)-(1)+3= -1
class NumArray(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.nums=list(nums)
self.sumArray=list(nums)
for i in range(1,len(nums)): #prefix sum
self.sumArray[i]+=self.sumArray[i-1]
def sumRange(self, left, right):
"""
:type left: int
:type right: int
:rtype: int
"""
return self.sumArray[right]-self.sumArray[left]+self.nums[left]
if __name__ == '__main__':
result = NumArray(nums= [-2, 0, 3, -5, 2, -1])
ans = result.sumRange(2, 5)
print(ans)
class NumArray {
public:
NumArray(vector<int>& nums) {
copy=nums;
sumArray=nums;
for (int i=1; i<nums.size(); i++){
sumArray[i]+=sumArray[i-1];
}
}
int sumRange(int left, int right) {
return sumArray[right]-sumArray[left]+copy[left];
}
private:
vector<int> copy;
vector<int> sumArray;
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* int param_1 = obj->sumRange(left,right);
*/
###### tags: Leetcode easy python c++ string Top 100 Liked Questions
Aug 21, 2023[題目連結:] https://leetcode.com/problems/koko-eating-bananas/ 題目: 解題想法: 此題為有n串香蕉,第i串有piles[i]根香蕉守衛h小時回來 設一小時能吃k根香蕉吃完第i串後無法再同一小時內吃另外第j串 若第i串有x根香蕉,且x<k,則依舊需要等該小時過完,才能繼續下一串,意思為: 若有餘數需無條件進位1小時 求k使得能以最慢速度吃完所有香蕉
Mar 30, 2023[題目連結:] https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/description/ 題目: 解題想法: 此題為給一target目標節點,返回所有跟target相距k步的節點各點值皆不重複 可往上拜訪父點,也可往下拜訪子點 DFS+BFS拜訪 所需工具:dic= collections.defaultdict(list){key:某點的值 ; value:與他相連的所有鄰居的值}
Mar 29, 2023[題目連結:] https://leetcode.com/problems/nim-game/description/ 題目: 解題想法: 此題目為給n個石頭,你與對手每次可以拿走1~3顆最先拿完的人獲勝 你先開始拿 判斷是否你能獲勝 基本的if else判斷是否為4的倍數即可
Mar 29, 2023or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up