LeetCode 1057. Campus Bikes
Posted 約束の空
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 1057. Campus Bikes相关的知识,希望对你有一定的参考价值。
直接根据最短distance greedy做。
用了优先队列,C++ less<type> 是大的先,所以我们可以重载<符号,把逻辑反过来。
class Solution { public: struct dist_pair{ int dist; int worker; int bike; bool operator<(const dist_pair &a) const { if (dist!=a.dist) return dist>a.dist; else if (worker!=a.worker) return worker>a.worker; return bike>a.bike; } }; vector<int> assignBikes(vector<vector<int>>& workers, vector<vector<int>>& bikes) { priority_queue<dist_pair> q; for (int i=0;i<workers.size();++i){ for (int j=0;j<bikes.size();++j){ int d = abs(workers[i][0] - bikes[j][0]) + abs(workers[i][1] - bikes[j][1]); q.push({d,i,j}); } } vector<int> assign(workers.size(),-1); vector<bool> visitedBike(bikes.size(),false); while (!q.empty()){ auto [d,i,j] = q.top(); q.pop(); if(assign[i]==-1 && visitedBike[j]==false){ visitedBike[j] = true; assign[i] = j; } } return assign; } };
第二种写法不用结构体,节省了空间复杂度,但是每次cmp的时候都要计算dist,但是时间会翻倍。
这里采用了 lambda funtion,注意 priority_queue 里 lambda 的写法。
class Solution { public: vector<int> assignBikes(vector<vector<int>>& workers, vector<vector<int>>& bikes) { auto cmp=[&](const pair<int,int> &a, const pair<int,int> &b){ int dist_a=dist(a.first,a.second,workers,bikes); int dist_b=dist(b.first,b.second,workers,bikes); if (dist_a!=dist_b) return dist_a>dist_b; if (a.first!=b.first) return a.first>b.first; return a.second>b.second; }; priority_queue<pair<int,int>,vector<pair<int,int>>,decltype(cmp)> q(cmp); for (int i=0;i<workers.size();++i) for (int j=0;j<bikes.size();++j) q.push({i,j}); vector<int> assign(workers.size(),-1); vector<bool> visitedBike(bikes.size(),false); while (!q.empty()){ auto [i,j] = q.top(); q.pop(); if(assign[i]==-1 && visitedBike[j]==false){ visitedBike[j] = true; assign[i] = j; } } return assign; } int dist(int i, int j, vector<vector<int>>& workers, vector<vector<int>>& bikes){ return abs(workers[i][0]-bikes[j][0])+abs(workers[i][1]-bikes[j][1]); } };
时间复杂度:mnlog(mn),因为有mn对pair。
以上是关于LeetCode 1057. Campus Bikes的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 1066. Campus Bikes II