分析:在整个数域范围上二分查找最小磁力的大小
然后记录这个最小磁力可以在position上放置几个球,根据球的数量与m的大小来决定二分范围
class Solution { public int maxDistance(int[] position, int m) { int n = position.length; Arrays.sort(position); int l = 0, r = position[n-1]; while(l <= r) { // 整个[l,r]范围上查询 int mid = l + (r - l) / 2; int t = 1, pre = 0; for(int i = 1; i < n; i++) { if(position[i] - position[pre] < mid) continue; t++; pre = i; } if(t >= m) l = mid + 1; // 放多了或者刚好还可能有剩余 距离加大 else r = mid - 1; // 放少了 距离减小 } return r; } }
class Solution { public int minDays(int[] bloomDay, int m, int k) { int n = bloomDay.length; if(n < m * k) return -1; int l = 1, r = 1000000000; while(l <= r) { int mid = (l + r) >> 1; int constant = 0, sum = 0; for(int num : bloomDay) { if(num <= mid) { constant++; } else { constant = 0; } if(constant == k) { constant = 0; sum++; } } if(sum >= m) { r = mid - 1; } else { l = mid + 1; } } return l; } }
class Solution { public int splitArray(int[] nums, int m) { int n = nums.length; int l = 0, r = 0; for(int num : nums) { l = Math.max(l,num); r += num; } while(l <= r) { int mid = l + (r - l) / 2; int cnt = 1, sum = 0; for(int num : nums) { sum += num; if(sum <= mid) continue; cnt++; sum = num; } if(cnt > m) l = mid + 1; else r = mid - 1; } return l; } }