C++ 中的无效交易

c++server side programmingprogramming更新于 2025/6/27 2:37:17

假设存在一些交易。如果满足 −,则交易可能无效。

  • 金额超过 1000 美元;

  • 如果该交易发生在另一城市的另一笔同名交易的 60 分钟内(含)。

此处,每个交易字符串 transactions[i] 由逗号分隔的值组成,分别代表交易名称、时间(以分钟为单位)、金额和城市。我们有一个交易列表,请找出可能无效的交易列表。因此,如果输入为 ["alice,20,800,mtv", "bob,50,1200,mtv"],那么答案将是 ["bob,50,1200,mtv"]。

为了解决这个问题,我们将遵循以下步骤 −

  • 定义一个集合 s。定义一个映射 m

  • 对于 i,范围从 0 到 t 的大小 – 1

    • x := t[i]

    • temp := node 使用字符串 x

    • for j in range 0 to size of m[temp name]

      • y := m[temp name][j]

      • 如果 y 的城市不是 temp 的城市,且 |y 的时间 – temp 的时间| −= 60

        • 将节点 y 作为字符串插入集合 s,并将 x 插入 s

    • 如果 temp 的数量 > 1000,然后将 x 插入 s

    • 将 temp 插入 m[temp 的名称]

  • 返回集合 s 中的项目

示例(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, ]

相关文章