classSolution { vector<int> convert(const string& s){ vector<int> ans(26); for (char c : s) { ++ans[c - 'a']; } return ans; } public: intminSteps(string s, string t){ auto count_s = convert(s); autocount_t = convert(t); int ans = 0; for (int i = 0; i < 26; ++i) { if (count_s[i] > count_t[i]) { ans += count_s[i] - count_t[i]; } } return ans; } };
1348. Tweet Counts Per Frequency
Use TreeMap to record tweets. Pay attention to the split points of the intervals, and find the tweets inside each interval according to those split points.
Time complexity:
recordTweet: O(log N)
getTweetCountsPerFrequency: O(N * log N * (endTime - startTime) / interval) Space complexity:
classTweetCounts { unordered_map<string, map<int, int>> string_map; public: TweetCounts() { } voidrecordTweet(string tweetName, int time){ ++string_map[tweetName][time]; } vector<int> getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime){ int interval = 0; if (freq == "hour") { interval = 3600; } elseif (freq == "day") { interval = 3600 * 24; } else { interval = 60; } constauto& m = string_map[tweetName]; vector<int> ans; int st = startTime; auto start_it = m.lower_bound(st); auto end_it = m.upper_bound(endTime); auto it = start_it; while (st <= endTime) { auto next_it = m.lower_bound(st + interval); int accu = 0; for (; it != next_it && it != end_it; ++it) { accu += it->second; } ans.push_back(accu); st += interval; } return ans; } };
/** * Your TweetCounts object will be instantiated and called as such: * TweetCounts* obj = new TweetCounts(); * obj->recordTweet(tweetName,time); * vector<int> param_2 = obj->getTweetCountsPerFrequency(freq,tweetName,startTime,endTime); */
1349. Maximum Students Taking Exam
A pretty hard problem. I learned the correct solution only after watching Hua Hua‘s video, so here is a friendly recommendation. Dynamic Programming (DP) plus state compression.
Here are several bitmask tricks:
No students to the left or right: (x & (x >> 1)) == 0
No student on the upper-left: (a & (b >> 1)) == 0
Enumerate all states according to the seats: state_enum = state & (state_enum - 1)
Time complexity: O(m * 2 ^ n * 2 ^ n), space complexity: O(m * 2 ^ n) -> O(2 ^ n).