leetcode1552. Magnetic Force Between Two Balls

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.

题目大意:宇宙Earth中,Rick发现了一种两个球间特殊形式的磁矩。rick有n个空篮子,第i个篮子在position[i]。marty有m个球,需要将这些球分进篮子中,以求得任意两球间的最小磁矩最大化。

思路(从别人思路归纳过来变成自己的,感谢leetcode精选这位朋友的思路和代码):最大化最小问题1. 先找出最小磁力的最小可能取值和最大可能取值。最小可能取值即为连续两个位置间的最小距离mn,最大可能取值为平均取值,m个球,需要m-1个间隔,球间的最大间隔diff为position[len-1]-positon[0],平均取值即为diff/(m-1)。2. 使用二分法进行搜索,找出最小磁矩的最大化。l = mn, r = diff/(m-1)。

  1. bool check(int x, vector& a, int m)函数
    x: 最小间隔
    a: 排序后的位置数组
    m: 球的个数
    使用变量cnt来记录间隔数,target记录最小间隔下的下一目标位置,遍历排序后的位置数组a,当条件a[i] < target && a[i+1] >= target成立时,累加间隔数,同时更新target变量。
  2. int maxDistance(vector& a, int m)
    a: 原始位置数组
    m: 球的个数
    先对位置数组进行排序,len为数组长度,diff为最大间隔(排序后的数组末位减去数组首位),mn为最小间隔。遍历数组更新最小间隔。l=mn, r=diff/(m-1)使用二分的思想来查找最大化最小间隔。

代码如下(再次感谢这位前辈的代码和思路,下面的代码是我理清逻辑后自己写的,但本身学习的就是这位前辈的代码,因此重复度很高):

class Solution {
public:
    bool check(int x, vector<int>& a, int m){
        int cnt = 0;
        int target = a[0] + x;
        for(int i = 0; i < a.size() - 1; i++){
            if(a[i] < target && a[i+1] >= target){
                cnt += 1;
                target = a[i+1] + x; 
            }
        }
        return cnt >= (m - 1);
    }

    int maxDistance(vector<int>& a, int m){
        sort(a.begin(), a.end());
        int len = a.size();
        int diff = a[len-1] - a[0];
        int mn = INT_MAX;
        for(int i = 0; i < len-1; i++){
            if(mn > a[i+1] - a[i]){
                mn = a[i+1] - a[i];
            }
        }

        int l = mn, r = diff/(m-1);
        while(l <= r){
            int mid = (l+r)/2;
            if(check(mid, a, m)){
                l = mid + 1;
            }
            else
            {
                r = mid - 1;
            }
        }
        return l-1;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值