- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 41 lines of Python from the credited upstream file best-reachable-tower.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution(object):6 def bestTower(self, towers, center, radius):7 """8 :type towers: List[List[int]]9 :type center: List[int]10 :type radius: int11 :rtype: List[int]12 """13 best = best_x = best_y = -114 for x, y, q in towers:15 if not abs(x-center[0])+abs(y-center[1]) <= radius:16 continue17 if q > best:18 best, best_x, best_y = q, x, y19 elif q == best and (x < best_x or (x == best_x and y < best_y)):20 best_x, best_y = x, y21 return [best_x, best_y] if best != -1 else [-1, -1]22 23 24252627class Solution2(object):28 def bestTower(self, towers, center, radius):29 """30 :type towers: List[List[int]]31 :type center: List[int]32 :type radius: int33 :rtype: List[int]34 """35 result = [1]*336 for x, y, q in towers:37 if not abs(x-center[0])+abs(y-center[1]) <= radius:38 continue39 result = min(result, [-q, x, y])40 return result[1:] if result[0] != 1 else [-1, -1]41