classSolution { public: intcountLargestGroup(int n){ unordered_map<int, int> seen; int largestSize = 0; for (int i = 1; i <= n; ++i) { int sumOfDigit = 0; int current = i; while (current > 0) { sumOfDigit += current % 10; current /= 10; } ++seen[sumOfDigit]; largestSize = max(largestSize, seen[sumOfDigit]); } int ans = 0; for (auto it = seen.begin(); it != seen.end(); ++it) { if (it->second == largestSize) ++ans; } return ans; } };
1400. Construct K Palindrome Strings
Count the number of characters that appear an odd number of times; it must be less than or equal to k. Also, since the required palindrome strings must be non-empty, we need s.size() >= k.
Time complexity: O(N), space complexity: O(1).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: boolcanConstruct(string s, int k){ if (s.size() < k) returnfalse; vector<int> count(26, 0); for (char c : s) { ++count[c - 'a']; } int single = 0; for (int i : count) { if (i % 2 == 1) ++single; } return single <= k; } };
1401. Circle and Rectangle Overlapping
Based on the four sides of the square, divide the space into 9 parts, and classify the circle center into 9 possible positions. For each case, it is easy to determine whether it overlaps with the square.
There is also a simpler method to implement in the discussion section, which quickly finds the point in the rectangle closest to a given point, the circle center.
1402. Reducing Dishes
Greedy. Sort first, then take the dishes with the largest satisfaction values until the suffix sum becomes less than 0.
Time complexity: O(N log N), space complexity: O(1).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: intmaxSatisfaction(vector<int>& satisfaction){ constint n = satisfaction.size(); sort(satisfaction.begin(), satisfaction.end()); int currentSum = 0; int suffixSum = 0; for (int i = n - 1; i >= 0; --i) { suffixSum += satisfaction[i]; if (suffixSum >= 0) { currentSum += suffixSum; } else { return currentSum; } } return currentSum; } };
My first submission used an N^2 solution: sort and then enumerate the starting point. It actually passed.