Leetcode 419. 甲板上的战舰

思路1:遍历数组并做标记

看到这道题很容易就想到,用一个标记数组,将遍历过的符合条件的军舰标记,然后扫描一遍,统计答案

class Solution {
    int cnt;
    int[][] book;
    public int countBattleships(char[][] board) {
        book = new int[board.length][board[0].length];
        for(int i = 0; i < board.length; i++ ) {
            for(int j = 0; j < board[0].length; j++ ){
                if(board[i][j] == 'X' && book[i][j] == 0){
                    for(int k = i; k < board.length && board[k][j] == 'X'; k++ ) {
                        book[k][j] = 1;
                    }
                    for(int k = j; k < board[0].length && board[i][k] == 'X'; k++ ) {
                        book[i][k] = 1;
                    }
                    cnt++;
                }
            }
        }
        return cnt;
    }
}

时间复杂度:O(m×n)
空间复杂度:O(m×n)

思路2:只统计起点

本来我以为今天的每日一题就这,但看了大佬的题解,就有一种豁然开朗的感觉。
对于每一个军舰,我们只需要统计它的起点即可,也就是,遍历数组时,当前遍历到 board[i][j] == ‘X’,如果board[i-1][j]和board[i][j-1]都不是 ‘X’ 那么他就是一个军舰的起点,那么我们让sum++,否则就不统计入答案。

class Solution {
    int cnt;
    public int countBattleships(char[][] board) {
        for(int i = 0; i < board.length; i++ ) {
            for(int j = 0; j < board[0].length; j++ ){
                if(i > 0 && board[i-1][j] == 'X')continue;
                if(j > 0 && board[i][j-1] == 'X')continue;
                cnt += board[i][j] == 'X'? 1 : 0;
            }
        }
        return cnt;
    }
}

时间复杂度:O(m×n)
空间复杂度:O(1)

大佬还是大佬,自愧不如。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值