官方解答 · 置頂Java
官方解答|帳戶交易報表
官方解答|帳戶交易報表
解題思路
建立三個 Account,各以 2 為初值。按 commands 原順序執行,存款不收費。
以下 B 是本筆指令執行前的來源帳戶餘額,A 是指令要求的正整數金額,F = 1 是固定費用。『餘額足夠』是指足以支付要求金額及費用,即 B >= A + F;不能只比較 B 與 A。
本題採『不得透支;不足則整筆拒絕』,提領與轉帳都使用同一規則:
- B >= A + F:接受並完整執行要求金額 A,來源帳戶扣除 A + F。
- B < A + F:整筆拒絕,不扣金額、不扣費用,所有帳戶保持原狀。 不得縮減要求金額,也不得讓來源帳戶餘額變成負數。
接受提領時,來源帳戶扣除 A + F;接受轉帳時,先確認可支付 A + F,再一次更新兩個帳戶:來源扣除 A + F,下一帳戶只增加要求金額 A,費用不進入任何帳戶。 拒絕指令不計成功,並計一次失敗。存入一定成功且不收費;接受的提領、轉帳各算一次成功。金額必須為正整數,沒有只扣費用的零金額交易。
最後輸出[帳號0餘額, 帳號1餘額, 帳號2餘額, 成功指令數]。
正確性與邊界
例如,提款前餘額 6、要求提領 9、費用 1:因 6 < 9 + 1,整筆拒絕,餘額仍為 6。
空 commands 不執行交易,帳戶仍為初值,成功及失敗次數皆為 0。
複雜度
設 m 為指令數。時間 O(m),額外空間 O(1),固定三個帳戶及固定大小回傳。
公開範例
輸入 {"commands": [[1, 1, 3]]},依上述步驟得到 [2, 2, 2, 0]。
下方程式可直接取代起始碼;使用 Java 11,入口為 Solution.solve。
CodeSprout 官方解答 · 題意分析、解題步驟與完整參考程式
import java.util.*;
public class Solution {
private static class Account {
private int balance;
Account(int initial) { balance = initial; }
void deposit(int amount) { balance += amount; }
int withdraw(int amount) {
if (balance < amount+1) return -1;
balance -= amount+1;
return amount;
}
int balance() { return balance; }
}
public static List<Integer> solve(int[][] commands) {
Account[] accounts = { new Account(2), new Account(2), new Account(2) };
int success = 0, failures = 0;
List<Integer> result = new ArrayList<>();
for (int[] command : commands) {
int type = command[0], id = command[1], amount = command[2];
boolean ok;
if (type == 0) { accounts[id].deposit(amount); ok = true; }
else {
int transferred = accounts[id].withdraw(amount);
ok = transferred != -1;
if (ok && type == 2) accounts[(id+1)%3].deposit(transferred);
}
if (ok) success++; else failures++;
}
for (Account a : accounts) result.add(a.balance());
result.add(success);
return result;
}
}
留言討論 0
登入 後就能留言,一起討論不同的寫法。