55
55
56
56
<!-- 这里可写通用的实现逻辑 -->
57
57
58
- ** 方法一:贪心**
58
+ ** 方法一:排序 + 贪心**
59
59
60
- 选出 ` aCost - bCost ` 最小的 N 个人,让他们飞往 a 市,其余人飞往 b 市。
60
+ 我们不妨先假设所有人都去 $b$ 市,然后我们要从中选出 $n$ 个人去 $a$ 市,使得总费用最小。如果一个人去 $a$ 市的费用比去 $b$ 市的费用小,我们把这个人从 $b$ 市调到 $a$ 市,这样总费用就会减少。因此,我们可以将所有人按照去 $a$ 市的费用与去 $b$ 市的费用的差值从小到大排序,然后选出前 $n$ 个人去 $a$ 市,剩下的人去 $b$ 市,这样总费用就是最小的。
61
+
62
+ 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组 ` costs ` 的长度。
63
+
64
+ 相似题目:
65
+
66
+ - [ 2611. 老鼠和奶酪] ( /solution/2600-2699/2611.Mice%20and%20Cheese/README.md )
61
67
62
68
<!-- tabs:start -->
63
69
@@ -91,32 +97,17 @@ class Solution {
91
97
}
92
98
```
93
99
94
- ### ** Go**
95
-
96
- ``` go
97
- func twoCitySchedCost (costs [][]int ) int {
98
- sort.Slice (costs, func (i, j int ) bool {
99
- return costs[i][0 ]-costs[i][1 ] < costs[j][0 ]-costs[j][1 ]
100
- })
101
- ans , n := 0 , len (costs)>>1
102
- for i := 0 ; i < n; i++ {
103
- ans += costs[i][0 ] + costs[i+n][1 ]
104
- }
105
- return ans
106
- }
107
- ```
108
-
109
100
### ** C++**
110
101
111
102
``` cpp
112
103
class Solution {
113
104
public:
114
105
int twoCitySchedCost(vector<vector<int >>& costs) {
115
- sort(costs.begin(), costs.end(), [ ] (const std:: vector<int >& a, const std:: vector<int >& b) {
116
- return a[ 0] - a[ 1] < ( b[ 0] - b[ 1] ) ;
106
+ sort(costs.begin(), costs.end(), [ ] (const vector<int >& a, const vector<int >& b) {
107
+ return a[ 0] - a[ 1] < b[ 0] - b[ 1] ;
117
108
});
109
+ int n = costs.size() / 2;
118
110
int ans = 0;
119
- int n = costs.size() >> 1;
120
111
for (int i = 0; i < n; ++i) {
121
112
ans += costs[ i] [ 0 ] + costs[ i + n] [ 1 ] ;
122
113
}
@@ -125,6 +116,35 @@ public:
125
116
};
126
117
```
127
118
119
+ ### **Go**
120
+
121
+ ```go
122
+ func twoCitySchedCost(costs [][]int) (ans int) {
123
+ sort.Slice(costs, func(i, j int) bool {
124
+ return costs[i][0]-costs[i][1] < costs[j][0]-costs[j][1]
125
+ })
126
+ n := len(costs) >> 1
127
+ for i, a := range costs[:n] {
128
+ ans += a[0] + costs[i+n][1]
129
+ }
130
+ return
131
+ }
132
+ ```
133
+
134
+ ### ** TypeScript**
135
+
136
+ ``` ts
137
+ function twoCitySchedCost(costs : number [][]): number {
138
+ costs .sort ((a , b ) => a [0 ] - a [1 ] - (b [0 ] - b [1 ]));
139
+ const n = costs .length >> 1 ;
140
+ let ans = 0 ;
141
+ for (let i = 0 ; i < n ; ++ i ) {
142
+ ans += costs [i ][0 ] + costs [i + n ][1 ];
143
+ }
144
+ return ans ;
145
+ }
146
+ ```
147
+
128
148
### ** ...**
129
149
130
150
```
0 commit comments