题目地址:
https://www.lintcode.com/problem/matrix-game/description
给定一个二维矩阵,两个人轮流取数,一个人取过某一列的数之后,另一个人就不能取这个列的别的数了。假设每个人都去选最大的数字,问最后两个人分差。
先求出每一列最大数,然后对其排序,然后模拟两个人轮流选的过程即可。代码如下:
import java.util.Arrays;
public class Solution {
/**
* @param grids: a integer matrix
* @return: return the difference between two people at last.
*/
public int MatrixGame(int[][] grids) {
// write your code here
if (grids == null || grids.length == 0 || grids[0].length == 0) {
return 0;
}
int[] max = new int[grids[0].length];
Arrays.fill(max, Integer.MIN_VALUE);
for (int i = 0; i < grids[0].length; i++) {
for (int j = 0; j < grids.length; j++) {
max[i] = Math.max(max[i], grids[j][i]);
}
}
Arrays.sort(max);
int res = 0, sign = 1;
for (int i = max.length - 1; i >= 0; i--) {
res += sign * max[i];
sign *= -1;
}
return res;
}
}
时间复杂度 O ( m n + n log n ) O(mn+n\log n) O(mn+nlogn),空间 O ( n ) O(n) O(n)(矩阵 m m m行 n n n列)。