1603. Design Parking System
仅供自己学习
思路:
直接定义每个类型的车的park数的变量,每次创建一个对象就载入值,每加入一辆车就减少一个park数即可
代码:
1 class ParkingSystem { 2 private: 3 int pb=0; 4 int pm=0; 5 int ps=0; 6 public: 7 ParkingSystem(int big, int medium, int small): pb(big),pm(medium),ps(small) {} 8 9 bool addCar(int carType) { 10 if(carType==1&&pb!=0){ 11 pb--; 12 return true; 13 } 14 else if(carType==2&&pm!=0){ 15 pm--; 16 return true; 17 } 18 else if(carType==3&&ps!=0){ 19 ps--; 20 return true; 21 } 22 return false; 23 } 24 }; 25 26 /** 27 * Your ParkingSystem object will be instantiated and called as such: 28 * ParkingSystem* obj = new ParkingSystem(big, medium, small); 29 * bool param_1 = obj->addCar(carType); 30 */
还有一种就是利用hash表,将cartype作为hash表的key值,parking数作为value值。之后有新的类型添加只需要重载一个构造方法即可。
其余不变,有新车加入就减一个位,不为0就返回true
1 class ParkingSystem { 2 public: 3 unordered_map<int,int> map; 4 ParkingSystem(int big, int medium, int small) { 5 map[1]=big; 6 map[2]=medium; 7 map[3]=small; 8 } 9 10 bool addCar(int carType) { 11 if(map[carType]!=0){ 12 map[carType]--; 13 return true; 14 } 15 return false; 16 } 17 }; 18 19 /** 20 * Your ParkingSystem object will be instantiated and called as such: 21 * ParkingSystem* obj = new ParkingSystem(big, medium, small); 22 * bool param_1 = obj->addCar(carType); 23 */