力扣每日一题-查询网格图中每一列的宽度-2024.4.27

力扣题目:查询网格图中每一列的宽度

题目链接:2639.查询网格图中每一列的宽度

题目描述

代码思路

双层for循环遍历整个矩阵容易想到,只要能想到使用整数转字符串的技巧("" + 字符串),即可完成题目

代码纯享版

java 复制代码
class Solution {
    public int[] findColumnWidth(int[][] grid) {
        int[] ans = new int[grid[0].length]; 
        for(int i = 0; i < grid[0].length; i++){
            int max = 0;
            for(int j = 0; j < grid.length; j++){
                String str = "" + grid[j][i];
                
                max = Math.max(max, str.length());
            }
            ans[i] = max;
        }
         return ans;
    }
}

代码逐行解析版

java 复制代码
class Solution {
    public int[] findColumnWidth(int[][] grid) {
        int[] ans = new int[grid[0].length]; //创建ans整数数据,记录每一列的宽度,即字符串长度最大值
        for(int i = 0; i < grid[0].length; i++){ 
            int max = 0; //记录最大值
            for(int j = 0; j < grid.length; j++){
                String str = "" + grid[j][i]; //将整数变成字符串,方便用字符串的length()方法直接计算字符串长度
                
                max = Math.max(max, str.length()); //记录最大值
            }
            ans[i] = max; //添加最大值
        }
         return ans;
    }
}
相关推荐
向阳@向远方5 分钟前
第二章 简单程序设计
开发语言·c++·算法
沉着的码农24 分钟前
【设计模式】基于责任链模式的参数校验
java·spring boot·分布式
Mr_Xuhhh36 分钟前
信号与槽的总结
java·开发语言·数据库·c++·qt·系统架构
纳兰青华1 小时前
bean注入的过程中,Property of ‘java.util.ArrayList‘ type cannot be injected by ‘List‘
java·开发语言·spring·list
好开心啊没烦恼1 小时前
Python 数据分析:DataFrame,生成,用字典创建 DataFrame ,键值对数量不一样怎么办?
开发语言·python·数据挖掘·数据分析
github_czy1 小时前
RRF (Reciprocal Rank Fusion) 排序算法详解
算法·排序算法
liulilittle1 小时前
VGW 虚拟网关用户手册 (PPP PRIVATE NETWORK 基础设施)
开发语言·网络·c++·网关·智能路由器·路由器·通信
coding and coffee1 小时前
狂神说 - Mybatis 学习笔记 --下
java·后端·mybatis
千楼1 小时前
阿里巴巴Java开发手册(1.3.0)
java·代码规范
Devil枫1 小时前
Kotlin高级特性深度解析
android·开发语言·kotlin