今天写leetcode 1552 题目,不断优化
class Solution:
def maxDistance(self, position: List[int], m: int) -> int:
def check(x: int) -> bool:
pre = position[0]
cnt = 1
for i in range(1, len(position)): #这里优化掉,不用range
if position[i] - pre >= x:
pre = position[i]
cnt += 1
return cnt >= m
position.sort()
left, right, ans = 1, position[-1] - position[0], -1
while left <= right:
mid = (left + right) // 2;
if check(mid):
ans = mid #这里可以优化掉,赋值
left = mid + 1
else:
right = mid - 1
return ans #返回left
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/magnetic-force-between-two-balls/solution/liang-qiu-zhi-jian-de-ci-li-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution:
def maxDistance(self, pp: List[int], m: int) -> int:
pp.sort()
k=len(pp)
def check(x):
cnt=1
p=pp[0]
for i in range(1,k):
if pp[i] -p >=x:
cnt+=1
p=pp[i]
return cnt>=m
left=1
right=pp[-1]
while left<right:
mid=left+right+1>>1
if check(mid):
left=mid
else:
right=mid-1
return left
再一次优化
class Solution:
def maxDistance(self, pp: List[int], m: int) -> int:
pp.sort()
k=len(pp)
def check(x):
cnt=1
p=pp[0]
for i in pp: #这里不切片,不range
if i -p >= x:
cnt+=1
p=i
return cnt>=m
left=1
right=pp[-1]
while left<right:
mid=left+right+1>>1 #右手打法
if check(mid):
left=mid
else:
right=mid-1
return left
网友评论