C++ 中的無效交易


假設有一些交易。如果滿足以下條件,則交易可能無效:

  • 金額超過 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 := 使用字串 x 建立的節點

    • 對於 j 從 0 到 m[temp 的名稱] 的大小

      • y := m[temp 的名稱][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, ]

更新於: 2020 年 5 月 2 日

170 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.