Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ธุรกรรมที่ไม่ถูกต้องใน C++

กำหนดรายการธุรกรรม แต่ละรายการเป็นสตริงรูปแบบ "name,time,amount,city" ธุรกรรมถือว่า ไม่ถูกต้อง (invalid) หาก:

  1. จำนวนเงิน (amount) เกิน 1000 ดอลลาร์, หรือ
  2. เกิดขึ้นภายใน 60 นาที (รวมขอบ) ของธุรกรรมอีกใบที่มี ชื่อเดียวกัน แต่ เมืองต่างกัน

ต้องการคืนรายการธุรกรรมที่ไม่ถูกต้องทั้งหมด

ตัวอย่าง: ["alice,20,800,mtv", "bob,50,1200,mtv"] → ["bob,50,1200,mtv"] (bob เกิน 1000)

ขั้นตอนการแก้ปัญหา

  1. แปลงแต่ละสตริงเป็นโครงสร้าง Node (name, city, time, amount)
  2. ใช้ map> จัดกลุ่มธุรกรรมตามชื่อ
  3. วนลูปทุกธุรกรรม:
    • เปรียบเทียบกับธุรกรรมเก่าของคนเดียวกัน: ถ้าเมืองต่างกันและ |time_diff| <= 60 ให้ทำเครื่องหมายทั้งคู่ว่า invalid
    • ถ้า 1000 ทำเครื่องหมาย invalid
  4. เก็บผลลัพธ์ใน set เพื่อไม่ซ้ำ แล้วคืนเป็นเวกเตอร์

ตัวอย่างโค้ด C++

#include <bits/stdc++.h>
using namespace std;

struct Node { string name, city; int time, amount; };

class Solution {
public:
    Node parse(string s) {
        Node ret; string temp = ""; int cnt = 0;
        for (char c : s) {
            if (c == ',') {
                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 = "";
            } else temp += c;
        }
        ret.city = temp; return ret;
    }
    vector<string> invalidTransactions(vector<string>& t) {
        set<string> s;
        unordered_map<string, vector<Node>> m;
        for (string& x : t) {
            Node cur = parse(x);
            for (Node& y : m[cur.name]) {
                if (y.city != cur.city && abs(y.time - cur.time) <= 60) {
                    s.insert(y.name + "," + to_string(y.time) + "," + to_string(y.amount) + "," + y.city);
                    s.insert(x);
                }
            }
            if (cur.amount > 1000) s.insert(x);
            m[cur.name].push_back(cur);
        }
        return vector<string>(s.begin(), s.end());
    }
};

int main() {
    vector<string> v1 = {"alice,20,800,mtv","bob,50,1200,mtv"};
    Solution ob;
    for (auto& s : ob.invalidTransactions(v1)) cout << s << ", ";
}

Input

["alice,20,800,mtv","bob,50,1200,mtv"]

Output

[bob,50,1200,mtv, ]