题目描述:
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.
Example 1:
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.
Example 2:
Input: transactions = ["alice,20,800,mtv","alice,50,1200,mtv"]
Output: ["alice,50,1200,mtv"]
Example 3:
Input: transactions = ["alice,20,800,mtv","bob,50,1200,mtv"]
Output: ["bob,50,1200,mtv"]
Constraints:
transactions.length <= 1000
- Each
transactions[i]
takes the form"{name},{time},{amount},{city}"
- Each
{name}
and{city}
consist of lowercase English letters, and have lengths between1
and10
. - Each
{time}
consist of digits, and represent an integer between0
and1000
. - Each
{amount}
consist of digits, and represent an integer between0
and2000
.
struct entry{
int time;
int amount;
string city;
string transaction;
};
class Solution {
public:
static bool comp(entry& a, entry& b)
{
return a.time<b.time;
}
vector<string> invalidTransactions(vector<string>& transactions) {
unordered_map<string,vector<entry>> hash;
for(auto s:transactions)
{
istringstream iss(s);
vector<string> v;
string tmp;
while(getline(iss,tmp,',')) v.push_back(tmp);
entry e={stoi(v[1]),stoi(v[2]),v[3],s};
hash[v[0]].push_back(e);
}
vector<string> result;
for(auto user:hash)
{ // 将同一个用户的转账按照时间排序
sort(user.second.begin(),user.second.end(),comp);
for(int i=0;i<user.second.size();i++)
{ // 为了判断当前转账是否合法,需要往两边遍历,如果找到60分钟内不同城市的转账,则为非法
bool invalid=false, over_1000=user.second[i].amount>1000;
for(int j=i+1;j<user.second.size();j++)
{
if(user.second[j].time-user.second[i].time>60) break;
if(user.second[i].city!=user.second[j].city)
{
invalid=true;
break;
}
}
for(int j=i-1;j>=0;j--)
{
if(user.second[i].time-user.second[j].time>60) break;
if(user.second[i].city!=user.second[j].city)
{
invalid=true;
break;
}
}
if(invalid||over_1000) result.push_back(user.second[i].transaction);
}
}
return result;
}
};