[LeetCode] Invalid Transactions

1169. Invalid Transactions

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.

You are given an array of strings transaction where transactions[i] consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction.

Return a list of transactions that are possibly invalid. You may return the answer in any order.

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 between 1 and 10.
  • Each {time} consist of digits, and represent an integer between 0 and 1000.
  • Each {amount} consist of digits, and represent an integer between 0 and 2000.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
struct Data {
string name;
int time;
int amount;
string city;
bool isPushed;

std::string toString() {
return name + "," + to_string(time) + "," + to_string(amount) + "," + city;
}
};

bool cmp(const Data &d1, const Data &d2) {
return d1.time < d2.time;
}

class Solution {
private:
Data getData(string &str) {
Data res;
stringstream ss;
int cnt = 0;
for (int i = 0; i < str.length(); i++) {
if (str[i] == ',') {
switch (cnt) {
case 0:
res.name = ss.str();
break;
case 1:
res.time = stoi(ss.str());
break;
case 2:
res.amount = stoi(ss.str());
res.city = str.substr(i + 1);
break;
}
cnt++;
ss.str("");
} else {
ss << str[i];
}
}
res.isPushed = false;

return res;
}

public:
vector<string> invalidTransactions(vector<string> &transactions) {
vector<string> res;
map<string, vector<Data>> myMap;
for (int i = 0; i < transactions.size(); i++) {
Data data = getData(transactions[i]);
myMap[data.name].push_back(data);
}

for (auto it = myMap.begin(); it != myMap.end(); it++) {
sort(it->second.begin(), it->second.end(), cmp);
for (int i = it->second.size() - 1, j = i - 1; i >= 0; --i) {
bool flag = false;
for (; j >= 0 && it->second[i].time - it->second[j].time <= 60; --j) {
if (it->second[j].city != it->second[i].city) {
if (!it->second[j].isPushed) {
res.push_back(it->second[j].toString());
it->second[j].isPushed = true;
}
flag = true;
}
}
if (!it->second[i].isPushed && (flag || it->second[i].amount > 1000)) {
res.push_back(it->second[i].toString());
it->second[i].isPushed = true;
}
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/02/10/PS/LeetCode/invalid-transactions/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.