This Monday I joined a LeetCode daily check-in and weekly contest group. It publishes rankings every week, and the bottom-ranked person sends a red packet; every day there is a designated problem to solve, and if you miss two consecutive days you also send a red packet. It is extremely intense and exciting. Contest leaderboard. This was my first contest since joining the group. Because the fourth problem was too hard, only around one hundred people solved it in total. In the group, only five people got AC.
1394. Find Lucky Integer in an Array
A warm-up problem. Pay attention to the data range and just count frequency.
Time complexity: O(N), space complexity: O(N).
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { public: intfindLucky(vector<int>& arr){ vector<int> count(501, 0); for (int i : arr) { ++count[i]; } for (int i = 500; i >= 1; --i) { if (count[i] == i) return i; } return-1; } };
1395. Count Number of Teams
Because the data scale is small, even an N^3 solution that enumerates all triples can pass. Here I used DP, with N^2 complexity. If using an order statistic tree, it can be further reduced to N log N.
Time complexity: O(N ^ 2), space complexity: O(N).
classUndergroundSystem { unordered_map<int, pair<string, int>> user_checkin_time; // 记录进站信息 map<pair<string, string>, pair<int, int>> interval_total_time_person_count; // 记录2站之间流量的信息,总时间、人数 public: UndergroundSystem() { } voidcheckIn(int id, string stationName, int t){ user_checkin_time[id] = {stationName, t}; } voidcheckOut(int id, string stationName, int t){ auto in = user_checkin_time[id]; auto& interval = interval_total_time_person_count[{in.first, stationName}]; interval.first += t - in.second; ++interval.second; user_checkin_time.erase(id); } doublegetAverageTime(string startStation, string endStation){ auto it = interval_total_time_person_count.find({startStation, endStation}); if (it == interval_total_time_person_count.end()) return-1; else returnstatic_cast<double>(it->second.first) / it->second.second; } };
/** * Your UndergroundSystem object will be instantiated and called as such: * UndergroundSystem* obj = new UndergroundSystem(); * obj->checkIn(id,stationName,t); * obj->checkOut(id,stationName,t); * double param_3 = obj->getAverageTime(startStation,endStation); */