1092.两地调度
题目描述:
公司计划面试 2N 人。第 i 人飞往 A 市的费用为 costs[i][0],飞往 B 市的费用为 costs[i][1]。
返回将每个人都飞到某座城市的最低费用,要求每个城市都有 N 人抵达。
示例:
输入:[[10,20],[30,200],[400,50],[30,20]]
输出:110
解释:
第一个人去 A 市,费用为 10。
第二个人去 A 市,费用为 30。
第三个人去 B 市,费用为 50。
第四个人去 B 市,费用为 20。
最低总费用为 10 + 30 + 50 + 20 = 110,每个城市都有一半的人在面试。
思路:
先遍历一遍数组costs,判断temp=costs[i][0]-costs[i][1],若大于则说明去b市花费小,并将temp存入br,反之则存入ar,这里temp等于0也是存入ar,最后min+temp.这样得到了 在a,b不一定满足等于n的情况下的最小值,
然后判断是a多了,还是b多了.
若是b多了,先将br排序,从小到大.(注意事项,因为ar与br的长度为costs.length,所以多余的部分会被0填充),在去掉0之后,min加上differ个最小值;
若是a多了,因为temp可能为0,所以ar排序后,跳过zlen=len-a 个值,再减去j = ar.length -zlen-1 个最大值.
代码:
class Solution {
public int twoCitySchedCost(int[][] costs) {
int min=0;
int len=costs.length;
int n=len/2;
int a=0;
int b=0;
int[] ar=new int[len];
int[] br=new int[len];
int temp=0;
for(int i=0;i<len;i++){
temp=costs[i][0]-costs[i][1];
if(temp>0){
br[b]=temp;
b++;
min+=costs[i][1];
}else if(temp<=0){
ar[a]=temp;
a++;
min+=costs[i][0];
}
}
if(b==n){
return min;
}
//与N的差值
int differ;
if (b > n) {
differ = b - n;
Arrays.sort(br);
int i = 0;
int j = 0;
while (i < differ) {
if (br[j] != 0) {
min = min + br[j];
i++;
}
j++;
}
} else if (b < n) {
differ = n - b;
int zlen=len-a;
Arrays.sort(ar);
int i = 0;
int j = ar.length -zlen-1;
while (i < differ) {
min=min-ar[j];
i++;
j--;
}
}
return min;
}
}
执行用时 :2 ms, 在所有 Java 提交中击败了96.09%的用户
内存消耗 :35.8 MB, 在所有 Java 提交中击败了100.00%的用户