【Leetcode】1029. Two City Scheduling
題目地址:
https://leetcode.com/problems/two-city-scheduling/
給定 2 n 2n 2n個面試者,給定他們分別去城市 A A A和城市 B B B的花費,以陣列形式表示,記為 C C C。公司打算讓其中 n n n個人去城市 A A A面試,讓剩下的 n n n個人去城市 B B B面試。問怎樣安排使得總花費最小。返回最小花費。
思路是貪心。假設先讓所有人都去城市 A A A面試,那麼總花費就是 ∑ i = 0 2 n − 1 C [ i ] [ 0 ] \sum_{i=0}^{2n-1}C[i][0] ∑i=02n−1C[i][0]。現在考慮將其中 n n n個人分配到城市 B B B中去,顯然應該儘可能將分配到 B B B之後花費會變小的人分配過去。對於下標為 i i i的人來說,將他分配到 B B B之後,總花費會減少 C [ i ] [ 1 ] − C [ i ] [ 0 ] C[i][1]-C[i][0] C[i][1]−C[i][0](這裡的意思是淨減少,有可能 C [ i ] [ 1 ] − C [ i ] [ 0 ] < 0 C[i][1]-C[i][0]<0 C[i][1]−C[i][0]<0,這樣分配過後總花費實際上是增加的)。那麼就應該將 C [ i ] [ 1 ] − C [ i ] [ 0 ] C[i][1]-C[i][0] C[i][1]−C[i][0]儘可能大的那些人分到 B B B那裡去,其餘分到 A A A那裡。所以思路就是,將陣列 C C C按照 C [ i ] [ 1 ] − C [ i ] [ 0 ] C[i][1]-C[i][0] C[i][1]−C[i][0]排序,前一半的人分到 A A A,其餘分到 B B B即可。程式碼如下:
import java.util.Arrays;
public class Solution {
public int twoCitySchedCost(int[][] costs) {
Arrays.sort(costs, (c1, c2) -> Integer.compare(c1[0] - c1[1], c2[0] - c2[1]));
int res = 0;
for (int i = 0; i < costs.length; i++) {
if (i < costs.length / 2) {
res += costs[i][0];
} else {
res += costs[i][1];
}
}
return res;
}
}
時間複雜度 O ( n log n ) O(n\log n) O(nlogn),空間 O ( 1 ) O(1) O(1)。
相關文章
- Leetcode Two SumLeetCode
- Leetcode Power of TwoLeetCode
- Leetcode 1 two sumLeetCode
- Leetcode-Two SumLeetCode
- Two Sum leetcode javaLeetCodeJava
- LeetCode | 1 Two SumLeetCode
- [LeetCode]1.Two SumLeetCode
- LeetCode----1. Two SumLeetCode
- LeetCode 1.Two NumsLeetCode
- LeetCode1:Two SumLeetCode
- Leetcode Divide Two IntegersLeetCodeIDE
- Leetcode Add Two NumbersLeetCode
- [LeetCode]1. Two SumLeetCode
- LeetCode OJ : 1 Two SumLeetCode
- LeetCode-1 Two SumLeetCode
- LeetCode | 349 Intersection Of Two ArraysLeetCode
- LeetCode 2 Add Two NumbersLeetCode
- LeetCode: Two sum(兩數之和)LeetCode
- Leetcode 231 Power of TwoLeetCode
- Leetcode 29 Divide Two IntegersLeetCodeIDE
- python: leetcode - 1 Two SumPythonLeetCode
- LeetCode Problem-Sum of Two IntegersLeetCode
- [leetCode][013] Two Sum 2LeetCode
- Leetcode Merge Two Sorted ListsLeetCode
- Leetcode Median of Two Sorted ArraysLeetCode
- Leetcode-Divide Two IntegersLeetCodeIDE
- [LeetCode] Two Sum 兩數之和LeetCode
- Leetcode-Add Two NumbersLeetCode
- Add Two Numbers leetcode javaLeetCodeJava
- Divide Two Integers leetcode javaIDELeetCodeJava
- leetcode-29. Divide Two IntegersLeetCodeIDE
- Leetcode 4 Median of Two Sorted ArraysLeetCode
- [LeetCode] 29. Divide Two IntegersLeetCodeIDE
- LeetCode #1:Two Sum(簡單題)LeetCode
- Leetcode 21 Merge Two Sorted ListsLeetCode
- LeetCode-2 Add Two NumbersLeetCode
- LeetCode 2. Add Two NumbersLeetCode
- Leetcode 231. Power of TwoLeetCode