1603. Design Parking System
Analysis
设计一个停车点的类。
Code
没啥说的,这个很简单。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23/**
* Your ParkingSystem object will be instantiated and called as such:
* ParkingSystem* obj = new ParkingSystem(big, medium, small);
* bool param_1 = obj->addCar(carType);
*/
class ParkingSystem {
public:
vector<int> park = vector<int>(4);
ParkingSystem(int big, int medium, int small) {
park[1] = big;
park[2] = medium;
park[3] = small;
}
bool addCar(int carType) {
if(!park[carType]) return false;
else {
park[carType]--;
return true;
};
}
};
303. Range Sum Query - Immutable
Analysis
这个题也很简单,因为数量级很小,直接用 vector 就行。但这样没什么意思,用普通的整型数组算了。
Code
method 1
直接用整型数组。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* int param_1 = obj->sumRange(left,right);
*/
class NumArray {
public:
int numbers[10005] = {0};
NumArray(vector<int>& nums) {
int size = nums.size();
for(int i = 0; i < size; i++) {
numbers[i] = nums[i];
}
}
int sumRange(int left, int right) {
int sum = 0;
while(left <= right) {
sum += numbers[left++];
}
return sum;
}
};
提交之后,时间与空间的消耗很大,这样的做法显然有点不值得。
method 2
因为这个题目只要求求和,所以,可以使用前缀和的思想来做。粗略估算一下极端情况的数值,$nums[i]$ 最大是 $10^5$,$nums$ 的大小最大为 $10^4$,那么计算情况就是 $10^9$ 和 $10^{-9}$,这是在 int 范围内的数字。1
2
3
4
5
6
7
8
9
10
11
12
13
14class NumArray {
public:
int numbers[10005] = {0};
NumArray(vector<int>& nums) {
int size = nums.size();
for(int i = 0; i < size; i++) {
numbers[i + 1] = nums[i] + numbers[i];
}
}
int sumRange(int left, int right) {
return numbers[right + 1] - numbers[left];
}
};
Summary
没啥说的,最后一天的题,都是比较简单的面对对象的思维。