C ++中的无效事务
假设有一些交易。如果满足以下条件,则交易可能无效:
金额超过$1000,或
如果发生在另一个城市的同名交易的60分钟内(包括60分钟)。
在这里,每个交易字符串transaction[i]由逗号分隔的值组成,这些值代表交易的名称,时间(以分钟为单位),金额和城市。我们有一个交易列表,找到一个可能无效的交易列表。因此,如果输入类似于[“alice,20,800,mtv”,“bob,50,1200,mtv”],则答案将是[“bob,50,1200,mtv”]。
为了解决这个问题,我们将遵循以下步骤-
定义一个集合。定义映射m
对于范围从0到t–1的i
y:=m[温度名称][j]
如果y的城市不是temp的城市,并且|y的时间–temp的时间|−=60
将节点y作为字符串插入sets,并将x插入s
x:=t[i]
temp:=使用字符串x的节点
对于介于0到m大小范围内的j[临时名称]
如果temp的数量>1000,则将x插入s
将temp插入m[temp的名称]
返回set中的项目
例子(C++)
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
class Node{
public:
string name;
string city;
int time;
int amount;
};
class Solution {
public:
Node getNode(string s){
string temp = "";
Node ret;
int cnt = 0;
for(int i = 0; i < s.size(); i++){
if(s[i] == ','){
if(cnt == 0){
ret.name = temp;
}
else if(cnt == 1){
ret.time = stoi(temp);
}
else if(cnt == 2){
ret.amount = stoi(temp);
} else {
ret.city = temp;
}
cnt++;
temp = "";
continue;
}
temp += s[i];
}
ret.city = temp;
return ret;
}
vector<string> invalidTransactions(vector<string>& t) {
set <string >s;
map <string ,vector < Node >> m;
for(int i = 0; i < t.size(); i++){
string x = t[i];
Node temp = getNode(x);
for(int j = 0; j < m[temp.name].size(); j++){
Node y = m[temp.name][j];
if(y.city != temp.city && abs(y.time - temp.time) <= 60){
s.insert(y.name + "," + to_string(y.time) + "," + to_string(y.amount) + "," + y.city);
s.insert(x);
}
}
if(temp.amount > 1000){
s.insert(x);
}
m[temp.name].push_back(temp);
}
vector <string> ret(s.begin(), s.end());
return ret;
}
};
main(){
vector<string> v1 = {"alice,20,800,mtv","bob,50,1200,mtv"};
Solution ob;
print_vector(ob.invalidTransactions(v1));
}输入值
["alice,20,800,mtv","bob,50,1200,mtv"]
输出结果
[bob,50,1200,mtv, ]