【設計】B007_LC_查詢無效交易(map + Info 類)

一、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];
        }
    } 
}

複雜度分析

  • 時間複雜度:O(...)O(...)
  • 空間複雜度:O(...)O(...)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章