力扣:1252. 奇数值单元格的数目

本文介绍了两种解决奇数值单元格计数问题的方法,分别是暴力解法和数组优化。通过实例展示了如何利用动态规划和数组操作快速找出给定二维数组中奇数元素的个数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.算法专练.力扣.奇数值单元格的数目;

/**
 * @author xnl
 * @Description:
 * @date: 2022/7/12   21:36
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] indices = {{0,1},{1,1}};
        System.out.println(solution.oddCells(2, 3, indices));
    }

    /**
     * 暴力解法
     * @param m
     * @param n
     * @param indices
     * @return
     */
    public int oddCells2(int m, int n, int[][] indices) {
        int[][] dp = new int[m][n];
        int x = indices.length;
        for (int i = 0; i < x; i++){
            int x1 = 0, y1 = 0;
            int x2 = indices[i][0];
            int y2 = indices[i][1];
            while (x1 < n){
                dp[x2][x1]++;
                x1++;
            }

            while (y1 < m){
                dp[y1][y2]++;
                y1++;
            }
        }

        int res = 0;
        for (int i = 0; i < m; i++){
            for (int j = 0; j < n; j++){
                if (dp[i][j] % 2 != 0){
                    res++;
                }
            }
        }
        return res;
    }


    /**
     * 数组优化
     *
     * @param m
     * @param n
     * @param indices
     * @return
     */
    public int oddCells(int m, int n, int[][] indices) {
        int[] row = new int[m];
        int[] col = new int[n];
        int res = 0;
        for (int[] index : indices) {
            row[index[0]]++;
            col[index[1]]++;
        }

        for (int i = 0; i < m; i++){
            for (int j = 0; j < n; j++){
                if (((row[i] + col[j]) & 1) != 0){
                    res++;
                }
            }
        }
        return res;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值