目录
题目:
思路:
其实就是要找每个房子落在哪个加热器之间,然后比较他们俩这种更近的那一侧。可以使用二分,也可以使用双指针,从头开始一起移动。
方法一:二分查找
class Solution:
def findRadius(self, houses: List[int], heaters: List[int]) -> int:
ans = 0
heaters.sort()
for house in houses:
j = bisect_right(heaters, house)
i = j - 1
rightDistance = heaters[j] - house if j < len(heaters) else float('inf')
leftDistance = house - heaters[i] if i >= 0 else float('inf')
curDistance = min(leftDistance, rightDistance)
ans = max(ans, curDistance)
return ans
1) j = bisect_right(heaters, house)
找到j满足 j = i+1
2)else float('inf') 意思是 正无穷的意思
后面要取最小值
所以和无穷大争最小值
必然是自己争到
方法二:排序 + 双指针
class Solution:
def findRadius(self, houses: List[int], heaters: List[int]) -> int:
ans = 0
houses.sort()
heaters.sort()
j = 0
for i, house in enumerate(houses):
curDistance = abs(house - heaters[j])
while j + 1 < len(heaters) and abs(houses[i] - heaters[j]) >= abs(houses[i] - heaters[j + 1]):
j += 1
curDistance = min(curDistance, abs(houses[i] - heaters[j]))
ans = max(ans, curDistance)
return ans
enumerate用法