[leetcode] 1552. Magnetic Force Between Two Balls

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 二分法的神仙操作以及在大佬提示下的二分万能套路

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值