Two City Scheduling Solutions in C++
Number 1029
Difficulty Easy
Acceptance 56.1%
Link LeetCode
Other languages —
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/two-city-scheduling/// Author : Hao Chen// Date : 2019-04-21class Solution {private:static int diff(vector<int>& x) {return x[1] - x[0];}static bool cmpfunc(vector<int>& lhs, vector<int>& rhs) {return diff(lhs) > diff(rhs);}public:// Just simply sort the array by comparing the different cost go to A city and B city// then the bigger difference would be in left and right side, and the smaller difference would be in the middle// We could simply let the first half go to A city, and the second half go to B city.int twoCitySchedCost(vector<vector<int>>& costs) {sort(costs.begin(), costs.end(), cmpfunc);int result = 0;int len = costs.size();for (int i=0; i<len/2; i++) {result += (costs[i][0] + costs[len-i-1][1]);}return result;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/two-city-scheduling//// Author : liuyubobobo/// Time : 2019-04-20#include <iostream>#include <vector>#include <algorithm>using namespace std;/// Sorting/// Time Complexity: O(nlogn)/// Space Complexity: O(1)class Solution {public:vector<vector<int>> allCellsDistOrder(int R, int C, int r0, int c0) {vector<vector<int>> res;for(int i = 0; i < R; i ++)for(int j = 0; j < C; j ++)res.push_back({i, j});sort(res.begin(), res.end(), [r0, c0](const vector<int>& v1, const vector<int>& v2){int dis1 = abs(v1[0] - r0) + abs(v1[1] - c0);int dis2 = abs(v2[0] - r0) + abs(v2[1] - c0);return dis1 < dis2;});return res;}};int main() {return 0;}