Skip to content

Commit 21f27cf

Browse files
author
Yi Gu
committed
[Array] Add a solution to Heaters
1 parent e66f573 commit 21f27cf

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

Diff for: Array/Heaters.swift

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/heaters/
3+
* Primary idea: Two pointers, get the closest heater for the house, and update radius
4+
* Time Complexity: O(nlogn), Space Complexity: O(1)
5+
*
6+
*/
7+
8+
class Heaters {
9+
func findRadius(_ houses: [Int], _ heaters: [Int]) -> Int {
10+
var i = 0, radius = 0
11+
let houses = houses.sorted(), heaters = heaters.sorted()
12+
13+
for house in houses {
14+
while i < heaters.count - 1 && 2 * house >= heaters[i] + heaters[i + 1] {
15+
i += 1
16+
}
17+
18+
radius = max(radius, abs(house - heaters[i]))
19+
}
20+
21+
return radius
22+
}
23+
}

0 commit comments

Comments
 (0)