最后剩下的问题是如何判断答案是否合法,即给定一个答案 x,是否存在一种放置方法使得相邻小球的间距最小值大于等于 x。这个问题其实很好解决,相邻小球的间距最小值大于等于 x,其实就等价于相邻小球的间距均大于等于 x。我们预先对给定的篮子的位置进行排序,那么从贪心的角度考虑,第一个小球放置的篮子一定是 position 最小的篮子,即排序后的第一个篮子。那么为了满足上述条件,第二个小球放置的位置一定要大于等于 position}[0]+x,接下来同理。因此我们从前往后扫 position 数组,看在当前答案 x 下我们最多能在篮子里放多少个小球,我们记这个数量为 cnt,如果 cnt 大于等于 m,那么说明当前答案下我们的贪心策略能放下 m 个小球且它们间距均大于等于 x ,为合法的答案,否则不合法。
classSolution { public: boolcheck(int x, vector<int>& position, int m){ int pre = position[0], cnt = 1; for (int i = 1; i < position.size(); ++i) { if (position[i] - pre >= x) { pre = position[i]; cnt += 1; } } return cnt >= m; } intmaxDistance(vector<int>& position, int m){ sort(position.begin(), position.end()); int left = 1, right = position.back() - position[0], ans = -1; while (left <= right) { int mid = (left + right) / 2; if (check(mid, position, m)) { ans = mid; left = mid + 1; } else { right = mid - 1; } } return ans; } };
classSolution { publicintmaxDistance(int[] position, int m) { Arrays.sort(position); intleft=1, right = position[position.length - 1] - position[0], ans = -1; while (left <= right) { intmid= (left + right) / 2; if (check(mid, position, m)) { ans = mid; left = mid + 1; } else { right = mid - 1; } } return ans; }
publicbooleancheck(int x, int[] position, int m) { intpre= position[0], cnt = 1; for (inti=1; i < position.length; ++i) { if (position[i] - pre >= x) { pre = position[i]; cnt += 1; } } return cnt >= m; } }
constcheck = (x, position, m) => { let pre = position[0], cnt = 1; for (let i = 1; i < position.length; ++i) { if (position[i] - pre >= x) { pre = position[i]; cnt += 1; } } return cnt >= m; } var maxDistance = function(position, m) { position.sort((x, y) => x - y); let left = 1, right = position[position.length - 1] - position[0], ans = -1; while (left <= right) { const mid = Math.floor((left + right) / 2); if (check(mid, position, m)) { ans = mid; left = mid + 1; } else { right = mid - 1; } } return ans; };
classSolution: defmaxDistance(self, position: List[int], m: int) -> int: defcheck(x: int) -> bool: pre = position[0] cnt = 1 for i inrange(1, len(position)): if position[i] - pre >= x: pre = position[i] cnt += 1 return cnt >= m
position.sort() left, right, ans = 1, position[-1] - position[0], -1 while left <= right: mid = (left + right) // 2; if check(mid): ans = mid left = mid + 1 else: right = mid - 1 return ans