classSolution { public: vector<vector<char>> rotateTheBox(vector<vector<char>>& box) { constint rows = box.size(); constint cols = box[0].size(); vector<vector<char>> ans(cols, vector<char>(rows, '.')); for (int i = 0; i < rows; ++i) { int stoneCnt = 0; for (int j = 0; j < cols; ++j) { if (box[i][j] == '#') { ++stoneCnt; } elseif (box[i][j] == '*') { // fall down ans[j][rows - 1 - i] = '*'; for (int k = 1; k <= stoneCnt; ++k) { ans[j - k][rows - 1 - i] = '#'; } stoneCnt = 0; } } for (int k = 1; k <= stoneCnt; ++k) { ans[cols - k][rows - 1 - i] = '#'; } } return ans; } };
时间复杂度: O(m * n),
空间复杂度: O(m * n).
1862. Sum of Floored Pairs
没啥好想法。首先尝试了暴力解,枚举所有的对:
1 2 3 4 5 6 7 8 9
classSolution: defsumOfFlooredPairs(self, nums: List[int]) -> int: MOD = 10**9 + 7 n = len(nums) ans = 0 for i inrange(n): for j inrange(n): ans += nums[j] // nums[i] return ans % MOD
classSolution { constint MOD = 1e9 + 7; public: intsumOfFlooredPairs(vector<int>& nums){ int ans = 0; sort(nums.begin(), nums.end()); constint MAX = nums.back(); constint n = nums.size(); int last = 0; for (int i = 0; i < n; ++i) { if (i > 0 && nums[i] == nums[i-1]) { ans = (ans + last) % MOD; continue; } last = 0; for (int j = 1; nums[i] * j <= MAX; ++j) { auto l = lower_bound(nums.begin() + i, nums.end(), nums[i] * j); auto r = lower_bound(l, nums.end(), nums[i] * (j + 1)); auto x = distance(l, r); last = (last + x * j) % MOD; } ans = (ans + last) % MOD; } return ans; } };
时间复杂度: O(N log N log N), 虽然有2个循环嵌套,但第二个其实是个调和级数。不过仍然TLE了。
空间复杂度: O(1).