Leetcode——1252.奇数值单元格的数目

题目

给你一个 n 行 m 列的矩阵,最开始的时候,每个单元格中的值都是 0。

另有一个索引数组 indices,indices[i] = [ri, ci] 中的 ri 和 ci 分别表示指定的行和列(从 0 开始编号)。

你需要将每对 [ri, ci] 指定的行和列上的所有单元格的值加 1。

请你在执行完所有 indices 指定的增量操作后,返回矩阵中 「奇数值单元格」 的数目。

思路

因为索引的数组,是一个n行2列的数组,其中,第一列改变的是行,第二列改变的是列。我们可以新建一个数组为n行m列,因为数组本身就默认值为0,并且改变之后,计算奇数个数即可。

代码

class Solution {
    public int oddCells(int n, int m, int[][] indices) {
        int test[][]=new int[n][m];

        //遍历索引数组第一个数,即改变行的
        for (int i=0;i<indices.length;++i)
        {
            for (int j=0;j<m;++j)
            {
                test[indices[i][0]][j]+=1;
            }

            for (int j=0;j<n;++j)
            {
                test[j][indices[i][1]]+=1;
            }
        }

        int count=0;
        for (int i=0;i<n;++i)
        {
            for (int j=0;j<m;++j)
                if ((test[i][j]&1)==1)
                    ++count;
        }
        return count;
    }
}

结果

没什么技术含量,就只是直接暴力一波就过了。
在这里插入图片描述

另外的思路

利用false代表偶数,利用true代表奇数

代码

class Solution {
    public int oddCells(int n, int m, int[][] indices) {
        //false 表示偶数
        boolean test[][]=new boolean[n][m];

        //遍历索引数组第一个数,即改变行的
        for (int i=0;i<indices.length;++i)
        {
            for (int j=0;j<m;++j)
            {
                test[indices[i][0]][j]=!test[indices[i][0]][j];
            }

            for (int j=0;j<n;++j)
            {
                test[j][indices[i][1]]=!test[j][indices[i][1]];
            }
        }

        int count=0;
        for (int i=0;i<n;++i)
        {
            for (int j=0;j<m;++j)
                if ((test[i][j]))
                    ++count;
        }
        return count;
    }
}

结果

本来以为少了判断与加减的操作应该会加快速度,但是结果显示这种利用 true 和 false 来表示结果的,速度反而降低了。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值