I continued to maintain good results, especially on the last problem, which was still quite hard. At the beginning I had no idea and even wanted to give up, but in the end I still solved the difficult problem through my own thinking.
1893. Check if All the Integers in a Range Are Covered
A warm-up problem. For each number in [left, right], check whether it is contained in one of the intervals in ranges.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: boolisCovered(vector<vector<int>>& ranges, int left, int right){ auto cover = [&](constint i) -> bool { for (constauto& range : ranges) { constint l = range[0], r = range[1]; if (l <= i && i <= r) returntrue; } returnfalse; }; for (int i = left; i <= right; ++i) { if (!cover(i)) returnfalse; } returntrue; } };
Time complexity: O((right - left) * ranges.length), space complexity: O(1).
1894. Find the Student that Will Replace the Chalk
First compute the prefix sum. Take k modulo the total sum to locate the traversal in the final round. Then use binary search to find the first position strictly greater than k; that is the student who needs to replace the chalk.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { using ll = longlong; public: intchalkReplacer(vector<int>& chalk, int k){ constint n = chalk.size(); vector<ll> presum(n + 1); presum[0] = 0; for (int i = 0; i < n; ++i) { presum[i+1] = presum[i] + chalk[i]; } if (k >= presum.back()) { k = k % presum.back(); } // the first index, presum[i] > k auto it = upper_bound(presum.begin(), presum.end(), k); returndistance(presum.begin(), it) - 1; } };
Time complexity: O(N + log N), N = chalk.length, space complexity: O(chalk.length).
Pay attention to the data range. The prefix sum may overflow int. I had one Runtime Error because of this. Changing it to long long was enough. LeetCode has had more and more overflow-trap cases recently. In the future, when encountering such problems, I need to estimate the maximum value first and use long long when it should be used.
1895. Largest Magic Square
Brute force: enumerate all squares from large to small, compute the sums of all rows, columns, and diagonals, then check whether they are equal. The only optimization is using prefix sums to quickly compute row and column sums.