原题说明
There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0], and the cost of flying the i-th person to city B is costs[i][1].
Return the minimum cost to fly every person to a city such that exactly N people arrive in each city.
Example 1:
Input:
[[10,20],[30,200],[400,50],[30,20]]
Output:110
Explanation:
The first person goes to city A for a cost of10.
The second person goes to city A for a cost of30.
The third person goes to city B for a cost of50.
The fourth person goes to city B for a cost of20.The total minimum cost is
10 + 30 + 50 + 20 = 110to have half the people interviewing in each city.
Note:
1 <= costs.length <= 100- It is guaranteed that costs.length is even.
1 <= costs[i][0], costs[i][1] <= 1000
解题思路
我们排序每一个面试者到A地和到B地cost之差,前N个(到A地cost较小的N个)取到A地cost,后N个取到B地cost,这样平均情况时间复杂度是NlogN
考虑到我们只需要到A地较小的元素在前半部分(较小元素之间的排序无关紧要),而到B地cost较小的元素在后半部分,所以可以考虑使用快速选择算法替代快速排序,将平均复杂度从NlogN减小到N
示例代码 (cpp)
1 | class Solution { |
示例代码 (java)
1 | class Solution { |
示例代码 (python)
1 | class Solution: |
复杂度分析
时间复杂度: O(N) for cpp, O(Nlog(N)) for java and python
空间复杂度: O(1)
归纳总结
我们在Youtube上更新了视频讲解,欢迎关注!