【Lintcode】1421. Matrix Game

题目地址:

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列)。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值