Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Bank System
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
//'main' method must be in a class 'Rextester'. //Compiler version 1.8.0_111 import java.util.*; import java.lang.*; class Rextester { public static void main(String args[]) { BankSystem bs = new BankSystem(); System.out.println(bs.withdraw(0, 100, 0)); // false bs.deposit(0, 100, 1); bs.withdraw(0, 30, 3); bs.deposit(1, 250, 2); bs.deposit(1, 2, 7); bs.deposit(1, 3, 9); System.out.println(Arrays.toString(bs.checkBalance(0, 0, 2))); // 0, 100 System.out.println(Arrays.toString(bs.checkBalance(1, 3, 8))); // 250, 252 } } /** * 设计一个银行帐户系统,实现: * 存钱(帐户id,存钱数目,日期) * 取钱(帐户id,存钱数目,日期) * 查账(帐户id,起始日期,结束日期): 只需要返回两个数值,一个是起始日期的balance,一个是结束日期的balance。 * 描述就是这么多,剩下的自己发挥。钱的类型用integer,日期什么的自定义,我直接拿了integer */ class BankSystem { Map<Integer, List<Record>> store; public BankSystem() { store = new HashMap<>(); } public boolean deposit(int id, int amount, int date) { if (!store.containsKey(id)) store.put(id, new ArrayList<>()); List<Record> records = store.get(id); Record last = records.size() > 0 ? records.get(records.size() - 1) : null; int currentBalance = last == null ? 0 : last.balance; if (currentBalance + amount < 0) return false; if (last != null && last.date == date) last.balance += amount; else records.add(new Record(date, currentBalance + amount)); return true; } public boolean withdraw(int id, int amount, int date) { return deposit(id, -amount, date); } public int[] checkBalance(int id, int startDate, int endDate) { return new int[] {checkBalance(id, startDate), checkBalance(id, endDate)}; } public int checkBalance(int id, int date) { if (!store.containsKey(id)) return 0; List<Record> records = store.get(id); int i = Collections.binarySearch(records, new Record(date, 0)); if (i >= 0) return records.get(i).balance; i = -i-1; return i == 0 ? 0 : records.get(i - 1).balance; } } class Record implements Comparable<Record> { int date; int balance; public Record(int d, int b) { date = d; balance = b; } @Override public int compareTo(Record that) { return this.date - that.date; } }
[
+
]
Show input
Compilation time: 1.04 sec, absolute running time: 0.19 sec, cpu time: 0.18 sec, memory peak: 18 Mb, absolute service time: 1,23 sec
edit mode
|
history
|
discussion
false [0, 100] [250, 252]