如果 y = y_0 是一个满足要求的答案,那么所有大于 y_0 的 y 同样也是满足要求的。因此存在一个 y = y_\textit{opt,使得当 y \geq y_\textit{opt 时都是满足要求的,当 y < y_\textit{opt 时都是不满足要求的。这个 y_\textit{opt 就是最终的答案。
classSolution { public: intminimumSize(vector<int>& nums, int maxOperations){ int left = 1, right = *max_element(nums.begin(), nums.end()); int ans = 0; while (left <= right) { int y = (left + right) / 2; longlong ops = 0; for (int x: nums) { ops += (x - 1) / y; } if (ops <= maxOperations) { ans = y; right = y - 1; } else { left = y + 1; } } return ans; } };
publicclassSolution { publicintMinimumSize(int[] nums, int maxOperations) { int left = 1, right = nums.Max(); int ans = 0; while (left <= right) { int y = (left + right) / 2; long ops = 0; foreach (int x in nums) { ops += (x - 1) / y; } if (ops <= maxOperations) { ans = y; right = y - 1; } else { left = y + 1; } } return ans; } }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution: defminimumSize(self, nums: List[int], maxOperations: int) -> int: left, right, ans = 1, max(nums), 0 while left <= right: y = (left + right) // 2 ops = sum((x - 1) // y for x in nums) if ops <= maxOperations: ans = y right = y - 1 else: left = y + 1 return ans
intminimumSize(int* nums, int numsSize, int maxOperations) { int left = 1, right = nums[0]; for (int i = 1; i < numsSize; i++) { right = MAX(right, nums[i]); } int ans = 0; while (left <= right) { int y = (left + right) / 2; longlong ops = 0; for (int i = 0; i < numsSize; i++) { ops += (nums[i] - 1) / y; } if (ops <= maxOperations) { ans = y; right = y - 1; } else { left = y + 1; } } return ans; }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
var minimumSize = function(nums, maxOperations) { let left = 1, right = _.max(nums); let ans = 0; while (left <= right) { const y = Math.floor((left + right) / 2); let ops = 0; for (const x of nums) { ops += Math.floor((x - 1) / y); } if (ops <= maxOperations) { ans = y; right = y - 1; } else { left = y + 1; } } return ans; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
funcminimumSize(nums []int, maxOperations int)int { max := 0 for _, x := range nums { if x > max { max = x } } return sort.Search(max, func(y int)bool { if y == 0 { returnfalse } ops := 0 for _, x := range nums { ops += (x - 1) / y } return ops <= maxOperations }) }