Google面试题:人和自行车匹配

题目参考这里,也是leetcode-cn举办的编程大赛的一道题,只想到了暴力法解决,超时了:

# -*- coding:utf-8 -*-
__author__ = 'ShawDa'

class Solution:
    def assignBikes(self, workers, bikes):
        res, dis_dict, index = [0]*len(workers), {}, list(range(len(workers)))
        for i, worker in enumerate(workers):
            for x, y in bikes:
                dis_dict[i] = dis_dict.get(i, []) + [(abs(worker[0]-x)+abs(worker[1]-y))]
        for _ in range(len(workers)):
            min_list = [float('inf')]*len(workers)
            for i in index:
                min_list[i] = min(dis_dict[i])
            ret = min_list.index(min(min_list))  # 工人号码
            bike_index = dis_dict[ret].index(min(min_list))
            for k, v in dis_dict.items():
                v[bike_index] = float('inf')
            res[ret] = bike_index
            index.remove(ret)
        return res

print(Solution().assignBikes([[0,0],[2,1]], [[1,2],[3,3]]))

你可能感兴趣的:(各种编程题,Python)