leetcode-1029-两地调度

如果i去A地花费10,去B地花费100
j去A地花费10,去B地花费110
那么j优先去A地
这是因为j去A比j去B节省了100
而i去A之比i去B节省了90
Intuition
How much money can we save if we fly a person to A vs. B? To minimize the total cost, we should fly the person with the maximum saving to A, and with the minimum - to B.

Example: [30, 100], [40, 90], [50, 50], [70, 50].
Savings: 70, 50, 0, -20.

Obviously, first person should fly to A, and the last - to B.

Solution
We sort the array by the difference between costs for A and B. Then, we fly first N people to A, and the rest - to B.

int twoCitySchedCost(vector<vector<int>>& cs, int res = 0) {
  sort(begin(cs), end(cs), [](vector<int> &v1, vector<int> &v2) {
    return (v1[0] - v1[1] < v2[0] - v2[1]);
  });
  for (auto i = 0; i < cs.size() / 2; ++i) {
    res += cs[i][0] + cs[i + cs.size() / 2][1];
  }
  return res;
}
Complexity Analysis
Runtime: O(n log n). We sort the array then go through it once.
Memory: O(1). We sort the array in-place.
class Solution {
	public int twoCitySchedCost(int[][] costs) {
		// 我们进可能让costs[i][1]-costs[i][0]大的去A
		Arrays.sort(costs, new Comparator<int[]>() {

			@Override
			public int compare(int[] o1, int[] o2) {
				// TODO Auto-generated method stub
				return o2[1] - o2[0] - o1[1] + o1[0];
			}
		});
		int ans = 0;
		int len = costs.length;
		for (int i = 0; i < len / 2; ++i)
			ans += costs[i][0] + costs[len / 2 + i][1];
		return ans;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值