【Leetcode】1169. Invalid Transactions

题目地址:

https://leetcode.com/problems/invalid-transactions/

给定一系列Transaction,要求返回其中所有的invalid的Transaction。一个Transaction是invalid的当:
1、其amount大于了 1000 1000 1000
2、存在一个name相同,city不同,并且时间相差 60 60 60分钟以内的另一个Transaction。

直接暴力做即可。用一个哈希表存某个人的所有Transaction,判断的时候直接暴力查找。代码如下:

import java.util.*;

public class Solution {
    
    class Transaction {
        String name, city;
        int time, amount;
        
        public Transaction(String trans) {
            String[] split = trans.split(",");
            this.name = split[0];
            this.time = Integer.parseInt(split[1]);
            this.amount = Integer.parseInt(split[2]);
            this.city = split[3];
        }
        
        @Override
        public String toString() {
            String[] ss = {name, String.valueOf(time), String.valueOf(amount), city};
            return String.join(",", ss);
        }
    }
    
    public List<String> invalidTransactions(String[] transactions) {
        List<String> res = new ArrayList<>();
        
        Map<String, List<Transaction>> map = new HashMap<>();
        for (String transaction : transactions) {
            Transaction tran = new Transaction(transaction);
            
            map.putIfAbsent(tran.name, new ArrayList<>());
            map.get(tran.name).add(tran);
        }
        
        for (Map.Entry<String, List<Transaction>> entry : map.entrySet()) {
            List<Transaction> transList = entry.getValue();
            
            for (int i = 0; i < transList.size(); i++) {
                Transaction curTrans = transList.get(i);
                if (curTrans.amount > 1000) {
                    res.add(curTrans.toString());
                } else {
                	// 找一下存不存在另一个交易name相同,city不同,并且时间相差60分钟以内
                    for (int j = 0; j < transList.size(); j++) {
                        if (j == i) {
                            continue;
                        }
    
                        Transaction another = transList.get(j);
                        if (Math.abs(another.time - curTrans.time) <= 60 && !another.city.equals(curTrans.city)) {
                            res.add(curTrans.toString());
                            break;
                        }
                    }
                }
                
            }
        }
        
        return res;
    }
}

时间复杂度 O ( ∑ n i 2 ) O(\sum n_i^2) O(ni2),空间 O ( ∑ n i ) O(\sum n_i) O(ni),其中 n i n_i ni表示每个人的交易的数量。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值