Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit d4d39cd

Browse files
committed
🐱(binary-search): 475. 供暖器
Add golang code.
1 parent 2960307 commit d4d39cd

File tree

1 file changed

+63
-1
lines changed

1 file changed

+63
-1
lines changed

docs/algorithm/research/binary-search/README.md

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -539,6 +539,10 @@ public class Solution extends GuessGame {
539539

540540
### 具体实现
541541

542+
<!-- tabs:start -->
543+
544+
#### **Python**
545+
542546
```python
543547
class Solution:
544548
def findRadius(self, houses: List[int], heaters: List[int]) -> int:
@@ -575,4 +579,62 @@ class Solution:
575579
res = max(house_res, res)
576580

577581
return res
578-
```
582+
```
583+
584+
#### **Go**
585+
586+
```go
587+
func findRadius(houses []int, heaters []int) int {
588+
sort.Ints(houses)
589+
sort.Ints(heaters)
590+
res := 0
591+
for _, house := range houses {
592+
left := 0
593+
right := len(heaters) - 1
594+
houseRes := 0
595+
// 二分查找
596+
for left < right {
597+
middle := left + (right - left) / 2
598+
if heaters[middle] < house {
599+
left = middle + 1
600+
} else {
601+
right = middle
602+
}
603+
}
604+
605+
if heaters[left] == house {
606+
houseRes = 0
607+
} else if heaters[left] < house { // 供暖器在左侧
608+
houseRes = house - heaters[left]
609+
} else { // 供暖器在右侧
610+
if left == 0 {
611+
houseRes = heaters[left] - house
612+
} else {
613+
houseRes = getMin(heaters[left] - house, house - heaters[left - 1])
614+
}
615+
}
616+
617+
res = getMax(res, houseRes)
618+
}
619+
620+
return res
621+
}
622+
623+
func getMin(a int, b int) int {
624+
if a < b {
625+
return a
626+
} else {
627+
return b
628+
}
629+
}
630+
631+
func getMax(a int, b int) int {
632+
if a > b {
633+
return a
634+
} else {
635+
return b
636+
}
637+
}
638+
```
639+
640+
<!-- tabs:end -->

0 commit comments

Comments
 (0)