2043. Simple Bank System
题目简介
这是一道系统设计题
题目回调用我们的构造函数 Bank 并且传入一个数字数组 balance,其长度为账户的数量,数组内的元素代表该帐号的余额
题目要求我们实现一系列的操作:
transfer:将account1账户的money转账到account2账户deposit:将money存入account账户withdraw:从account账户取出money
解题思路
只需要注意这些操作失败的原因有两个:
- 该帐号不存在:
account > balance.length - 该帐号转出的钱比当前存款多:
money > balance[account - 1]
Javascript
/**
* @param {number[]} balance
*/
var Bank = function (balance) {
this.balance = balance
this.len = balance.length
};
/**
* @param {number} account1
* @param {number} account2
* @param {number} money
* @return {boolean}
*/
Bank.prototype.transfer = function (account1, account2, money) {
if (account1 > this.len || account2 > this.len || this.balance[account1 - 1] < money) {
return false
}
this.balance[account1 - 1] -= money
this.balance[account2 - 1] += money
return true
};
/**
* @param {number} account
* @param {number} money
* @return {boolean}
*/
Bank.prototype.deposit = function (account, money) {
if (account > this.len) {
return false
}
this.balance[account - 1] += money
return true
};
/**
* @param {number} account
* @param {number} money
* @return {boolean}
*/
Bank.prototype.withdraw = function (account, money) {
if (account > this.len || this.balance[account - 1] < money) {
return false
}
this.balance[account - 1] -= money
return true
};
/**
* Your Bank object will be instantiated and called as such:
* var obj = new Bank(balance)
* var param_1 = obj.transfer(account1,account2,money)
* var param_2 = obj.deposit(account,money)
* var param_3 = obj.withdraw(account,money)
*/