Build Post Office
Given a 2D grid, each cell is either an house 1 or empty 0 (the number zero, one), find the place to build a post office, the distance that post office to all the house sum is smallest. Return the smallest distance. Return -1 if it is not possible.
Notice
You can pass through house and empty.
You only build post office on an empty.
Example
Given a grid:
0 1 0 0
1 0 1 1
0 1 0 0
return 6. (Placing a post office at (1,1), the distance that post office to all the house sum is smallest.)
分析
先考虑对于一维数组,计算数x到各个数值的距离
for example: A = [1, 2, 5, 4,6]
x = 3时: dis(A, 3) = |1 - 3|+ |2 - 3| + |4 - 3| + |5 - 3| + |6 - 3|
优化方法是:
1. 先排序A
2. 二分搜索找到3 应该插入的位置: A: [1, 2, 4 , 5, 6],二分搜索得知3应该插入到index = 2 的位置
3. 对于A中位于index = 2之前的数,它们到3的距离是:
smallPartDis = (3 -1) + (3 - 2) = 3 * 2 - (1 + 2)= 3 * id - (1 + 2)
对于A中位于index = 2之后的数,它们到3的距离是:
largePartDis = (4 -3) + (5 - 3) + (6 - 3)= (4 + 5 + 6) - 3 * 3
= (4 + 5 + 6) - 3 * (A.size() - id)
4. 为方便计算,我们算出A的prefix sum, 初始化preSum size 为A.size() + 1, preSum[0] = 0
这样:
smallPartDis = 3 * 2 - preSum[2]
largePartDis = preSum.back() - preSum[id] - 3 * (A.size() - id)
对于二维数组, (x, y) 到各个post office的距离是:
dis = |x1 - x| + |y1 - y| + |x2 - x| + |y2 - y| + |x3 - x| + |y3 - y|
可以转化为两个对于x 和y的一维数组:
dis = (|x1 - x| + + |x2 - x| + |x3 - x|) + (|y1 - y| + |y2 - y| + |y3 - y|)答案
Last updated
Was this helpful?