Description
In universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.
Rick stated that magnetic force between two different balls at positions x and y is |x - y|.
Given the integer array position and the integer m. Return the required force.
Example 1:
Input: position = [1,2,3,4,7], m = 3
Output: 3
Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.
Example 2:
Input: position = [5,4,3,2,1,1000000000], m = 2
Output: 999999999
Explanation: We can use baskets 1 and 1000000000.
Constraints:
- n == position.length
- 2 <= n <= 10^5
- 1 <= position[i] <= 10^9
- All integers in position are distinct.
- 2 <= m <= position.length
分析
题目的意思是:给你一个数组,要求你放m个球,使得球与球之间的最小间隔最大,球能够放的位置在position里面。这道题我一开始没看懂是什么意思,后面才发现是跟以前我见过的二叉查找树找符合条件的切分值一样的,二分查找首先找到最大值,即position数组排序后,最后一个值-最开始的值。然后遍历找最大间隔,然后根据遍历的最大间隔来看看能放多少个球,如果count(ball)<m,说明间隔太大了,需要减小;如果count(ball)>m,说明间隔太小了,需要增大。遍历的时候记录临界值mid就是最终满足题目要求的答案了。
- 注意我search 函数里面res统计量初始化为1,表示最开始的位置需要占用一个球;maxDistance里面的res记录的是mid的值。
代码
class Solution:
def maxDistance(self, position: List[int], m: int) -> int:
n=len(position)
position.sort()
low=0
high=position[n-1]-position[0]
res=0
while(low<=high):
mid=low+(high-low)//2
if(self.search(mid,position)<m):
high=mid-1
else:
low=mid+1
res=mid
return res
def search(self,diff,position):
res=1
for i in range(len(position)):
if(i==0):
prev=position[i]
elif(position[i]-prev>=diff):
res+=1
prev=position[i]
return res
参考文献
[LeetCode] Leetcode 1552. Magnetic Force Between Two Balls 二分法的神仙操作以及在大佬提示下的二分万能套路