classSolution { public: intminCharacters(string a, string b){ int ans = a.size() + b.size(); auto calculatePresum = [&](const string& x) -> vector<int> { vector<int> ans(26, 0); for (char c : x) { ++ans[c - 'a']; } for (int i = 1; i < 26; ++i) { ans[i] += ans[i - 1]; } return ans; }; auto op12 = [&](const string& a, const string& b) -> void { // 26 * (a.size() + b.size()) auto presumA = calculatePresum(a); auto presumB = calculatePresum(b); // b >= splitPoint, a < splitPoint for (int splitPoint = 1; splitPoint < 26; ++splitPoint) { int need = 0; // a need need += a.size() - presumA[splitPoint - 1]; // b need need += presumB[splitPoint - 1]; ans = min(ans, need); } }; // 1, 2 op12(a, b); op12(b, a); // 3 // size 和 - 众数 { unordered_map<char, int> cnt; for (char c : a) { ++cnt[c]; } for (char c : b) { ++cnt[c]; } int maxCnt = 0; for (auto p : cnt) { maxCnt = max(maxCnt, p.second); } ans = min(ans, static_cast<int>(a.size() + b.size()) - maxCnt); } return ans; } };
Time complexity: O(n + 26), space complexity: O(26).
1738. Find Kth Largest XOR Coordinate Value
Dynamic programming. In fact, during the contest I made it too complicated. I used three DP arrays to represent rectangle XOR values, row XOR values, and column XOR values. But based on the properties of XOR, namely commutativity and cancellation, maintaining one rectangle XOR value is enough.
classSolution { public: intkthLargestValue(vector<vector<int>>& matrix, int k){ constint m = matrix.size(); constint n = matrix[0].size(); auto rows = matrix; auto cols = matrix; vector<int> nums; nums.reserve(m * n); nums.push_back(matrix[0][0]); for (int i = 1; i < m; ++i) { cols[i][0] = cols[i-1][0] ^ matrix[i][0]; matrix[i][0] ^= matrix[i-1][0]; nums.push_back(matrix[i][0]); } for (int j = 1; j < n; ++j) { rows[0][j] = rows[0][j-1] ^ matrix[0][j]; matrix[0][j] ^= matrix[0][j-1]; nums.push_back(matrix[0][j]); } for (int i = 1; i < m; ++i) { for (int j = 1; j < n; ++j) { rows[i][j] = rows[i][j-1] ^ matrix[i][j]; cols[i][j] = cols[i-1][j] ^ matrix[i][j]; matrix[i][j] ^= matrix[i-1][j-1] ^ rows[i][j-1] ^ cols[i-1][j]; nums.push_back(matrix[i][j]); } } sort(nums.begin(), nums.end(), greater<int>()); return nums[k-1]; } };
Time complexity: O(m * n), space complexity: O(1), if matrix is reused and rows, cols are not needed.
1739. Building Boxes
Binary search. Determine the number of boxes on the bottom layer, then calculate how many boxes it can hold at most. According to the greedy idea, every layer should be squeezed into the corner as much as possible, forming an arithmetic sequence.