[Leetcode] Binary search -- 475. Heaters
Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses.
Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters.
So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters.
https://leetcode.com/problems/heaters/#/description
===========
Solution:
- 1st try, naive method. TLE using python.
The idea is to try iterate every house in houses hs, then we use hs to compare with each heater and get smallest distance "dist". So we have distance sets "dists"
find the maximum distance s from dists as the final answer, which is the minimum radius standard of heaters.
time complexity o(m*n), where m = len(houses), n = len(heaters)
1 ansMax = 0 2 houses.sort() 3 heaters.sort() 4 for hs in houses: 5 minDiff = 2**31 #get min 6 for ht in heaters: 7 if abs( hs -ht) < minDiff: 8 minDiff = abs(ht -hs) 9 10 if minDiff > ansMax: 11 ansMax = minDiff 12 return ansMax
2. Use binary search. The idea is similar as above. But it finds the left index of the most closest smaller(equal) ele, the right index closest bigger (equal) ele; then we compare to get the smallest distance "dist" for each position ; ( the function same as the bisect algorithm in python) , then we find the maximum distance s from dists as the final answer, which is the minimum radius standard of heaters.
Time complexity is o(mlogm+nlogn + m*lgn)
1 def binarySearch(lst, ele): 2 if len(lst) == 1: 3 return (0, 0) 4 l = 0 5 h = len(lst) - 1 6 while (l <= h): 7 mid = (l+h)/2 8 if lst[mid] == ele: 9 return (mid, mid) 10 elif lst[mid] < ele: 11 l = mid + 1 12 else: 13 h = mid - 1 14 return (l-1, l) #return left, right index 15 16 houses.sort() 17 heaters.sort() 18 ansMax = 0 19 for hs in houses: 20 (l, r) = binarySearch(heaters, hs) 21 #print('l, r: ', l,r ) 22 if r > len(heaters)-1: #only left is valid 23 minDiff = abs(hs- heaters[l]) 24 elif l < 0: 25 minDiff = abs(heaters[r] - hs) 26 else: 27 minDiff = min(abs(hs - heaters[l]), abs(heaters[r] -hs)) 28 #print('lminDi: ', minDiff ) 29 if minDiff > ansMax: 30 ansMax = minDiff 31 return ansMax
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步