classSolution { public: vector<int> frequencySort(vector<int>& nums){ unordered_map<int, int> cnt; for (int i : nums) { ++cnt[i]; } using pii = pair<int,int>; vector<pii> frequency; for (constauto& p : cnt) { frequency.emplace_back(p.second, p.first); } sort(frequency.begin(), frequency.end(), [&](constauto& a, constauto& b) -> bool { if (a.first == b.first) { return a.second > b.second; } else { return a.first < b.first; } }); vector<int> ans; for (constauto& p : frequency) { for (int i = 0; i < p.first; ++i) { ans.push_back(p.second); } } return ans; } };
Time complexity: O(N log N), space complexity: O(N).
5540. Widest Vertical Area Between Two Points Containing No Points
Although it looks complicated, it is actually just sorting by x and finding the largest gap. The problem statement deliberately made it sound harder and led everyone around in a circle.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public: intmaxWidthOfVerticalArea(vector<vector<int>>& points){ constint n = points.size(); vector<int> x; x.reserve(n); for (constauto& v : points) { x.push_back(v[0]); } sort(x.begin(), x.end()); int ans = 0; int lastx = x[0]; for (int i = 1; i < n; ++i) { ans = max(ans, x[i] - lastx); lastx = x[i]; } return ans; } };
Time complexity: O(N log N), space complexity: O(N).
5541. Count Substrings That Differ by One Character
This problem is also brute force. But at first I overcomplicated it and thought brute force was N^4, while actually it is N^3. So I skipped it and did the fourth problem first. After coming back, I still tried to use a so-called 25*N^3 algorithm and TLEed twice. After my roommate reminded me, I suddenly realized that it really was brute force.
classSolution { public: intcountSubstrings(string s, string t){ int ans = 0; for (int si = 0; si < s.size(); ++si) { for (int sj = 1; si + sj <= s.size(); ++sj) { for (int ti = 0; ti < t.size(); ++ti) { if (ti + sj > t.size()) break; int diff = 0; for (int x = 0; x < sj; ++x) { if (s[si + x] != t[ti + x]) { ++diff; if (diff > 1) goto end; } } if (diff == 1) ++ans; end:; } } } return ans; } };
Time complexity: O(N^3), space complexity: O(1).
5542. Number of Ways to Form a Target String Given a Dictionary
Classic DP. dp(begin, i) represents the number of ways to form target[i:] starting from the begin-th character of words. The state transition equation is: dp(begin, i) = dp(begin + 1, i + 1) * (the number of times target[i] appears in words[j][begin]) + dp(begin + 1, i)