一、Problem
A transaction is possibly invalid if:
the amount exceeds $1000, or;
if it occurs within (and including) 60 minutes of another transaction with the same name in a different city.
Each transaction string transactions[i] consists of comma separated values representing the name, time (in minutes), amount, and city of the transaction.
Given a list of transactions, return a list of transactions that are possibly invalid. You may return the answer in any order.
Input: transactions = ["alice,20,800,mtv","alice,50,100,beijing"]
Output: ["alice,20,800,mtv","alice,50,100,beijing"]
Explanation: The first transaction is invalid because the second transaction occurs within a difference of 60 minutes,
have the same name and is in a different city. Similarly the second one is invalid too.
二、Solution
方法一:模拟
一个人可能会有多个交易,所以 map 中的 key 只能为 name,然后 value 为该人的交易信息。
class Solution {
public List<String> invalidTransactions(String[] ts) {
Map<String, List<Info>> mp = new HashMap<>();
Set<Integer> del = new HashSet<>();
for (int i = 0; i < ts.length; i++) {
Info cur = new Info(i, ts[i]);
if (cur.amount > 1000)
del.add(cur.id);
if (mp.containsKey(cur.name)) {
List<Info> ins = mp.get(cur.name);
for (Info in : ins) if (!cur.city.equals(in.city) && Math.abs(cur.time - in.time) <= 60) {
del.add(in.id);
del.add(cur.id);
}
} else {
mp.put(cur.name, new ArrayList<>());
}
mp.get(cur.name).add(cur);
}
List<String> ans = new LinkedList<>();
for (int id : del) {
ans.add(ts[id]);
}
return ans;
}
class Info {
int id, time, amount;
String name, city;
Info(int id, String t) {
String[] ss = t.split(",");
this.id = id;
name = ss[0];
time = Integer.parseInt(ss[1]);
amount = Integer.parseInt(ss[2]);
city = ss[3];
}
}
}
复杂度分析
- 时间复杂度: ,
- 空间复杂度: ,