Skip to content

Commit

Permalink
[Array] Add a solution to Heaters
Browse files Browse the repository at this point in the history
  • Loading branch information
Yi Gu committed Jan 7, 2017
1 parent e66f573 commit 21f27cf
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions Array/Heaters.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
* Question Link: https://leetcode.com/problems/heaters/
* Primary idea: Two pointers, get the closest heater for the house, and update radius
* Time Complexity: O(nlogn), Space Complexity: O(1)
*
*/

class Heaters {
func findRadius(_ houses: [Int], _ heaters: [Int]) -> Int {
var i = 0, radius = 0
let houses = houses.sorted(), heaters = heaters.sorted()

for house in houses {
while i < heaters.count - 1 && 2 * house >= heaters[i] + heaters[i + 1] {
i += 1
}

radius = max(radius, abs(house - heaters[i]))
}

return radius
}
}

0 comments on commit 21f27cf

Please sign in to comment.