Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
campus-bikes.py 1.09 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2019-06-03 01:47 +08:00 . Create campus-bikes.py
# Time: O((w * b) * log(w * b))
# Space: O(w * b)
import heapq
class Solution(object):
def assignBikes(self, workers, bikes):
"""
:type workers: List[List[int]]
:type bikes: List[List[int]]
:rtype: List[int]
"""
def manhattan(p1, p2):
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
distances = [[] for _ in xrange(len(workers))]
for i in xrange(len(workers)):
for j in xrange(len(bikes)):
distances[i].append((manhattan(workers[i], bikes[j]), i, j))
distances[i].sort(reverse = True)
result = [None] * len(workers)
lookup = set()
min_heap = []
for i in xrange(len(workers)):
heapq.heappush(min_heap, distances[i].pop())
while len(lookup) < len(workers):
_, worker, bike = heapq.heappop(min_heap)
if bike not in lookup:
result[worker] = bike
lookup.add(bike)
else:
heapq.heappush(min_heap, distances[worker].pop())
return result
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助