鱼C论坛

 找回密码
 立即注册
查看: 2115|回复: 0

[学习笔记] Leetcode 1552. Magnetic Force Between Two Balls

[复制链接]
发表于 2020-9-16 04:33:27 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
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, 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:

Screenshot from 2020-09-15 16-33-01.png

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 <= 10^9
All integers in position are distinct.
2 <= m <= position.length

  1. class Solution:
  2.     def maxDistance(self, position: List[int], m: int) -> int:
  3.         position.sort()
  4.         N = len(position)
  5.         
  6.         left, right = 0, position[-1] - position[0]
  7.         
  8.         while left + 1 < right:
  9.             mid = int((right - left) / 2 + left)
  10.             
  11.             if self.count(mid, position) >= m:
  12.                 left = mid
  13.             else:
  14.                 right = mid
  15.         
  16.         if self.count(right, position) == m:
  17.             return right
  18.         return left
  19.    
  20.     def count(self, n: int, position: List[int]) -> int:
  21.         ans, curr = 1, position[0]
  22.         
  23.         for i in range(1, len(position)):
  24.             if position[i] - curr >= n:
  25.                 curr = position[i]
  26.                 ans += 1
  27.                
  28.         return ans
复制代码

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-20 11:11

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表