leetcode每日一题(20241203)

leetcode每日一题(20241203)

3274.检查棋盘方格颜色是否相同 题目描述:

bash 复制代码
给你两个字符串 coordinate1 和 coordinate2,代表 8 x 8 国际象棋棋盘上的两个方格的坐标。
以下是棋盘的参考图。

今天是简单题,行 为偶数时候 列为奇数 是黑色的 反之为白色 ;行 为奇数时候 列为偶数 是黑色 反之为白色(行从1开始,列从0开始的)

java 复制代码
class Solution {
    public boolean checkTwoChessboards(String coordinate1, String coordinate2) {
        return getColor(coordinate1)==getColor(coordinate2);
    }
    public int getColor(String coordinate){
        int col=coordinate.charAt(0)-'a';
        int row=coordinate.charAt(1)-'0';
        if(row%2==0){
            return col%2==0?0:1;
        }else{
            return col%2==0?1:0;
        }
    }
}

今天还写了一道之前的:

3101 交替子数组计数 题目描述:

bash 复制代码
给你一个二进制数组nums 。
如果一个子数组
中 不存在 两个 相邻 元素的值 相同 的情况,我们称这样的子数组为 交替子数组 。
返回数组 nums 中交替子数组的数量。

第一次看题目写的:

java 复制代码
class Solution {
    public long countAlternatingSubarrays(int[] nums) {
        int len=nums.length;
        int count=1;
        long res=0L;
        for(int i=1;i<len;i++){
            if(nums[i]==nums[i-1]){
                res+=getSum(count);
                count=1;
            }else{
                count++;
            }
        }
        res+=getSum(count);
        return res;
    }
    public long getSum(int n){
        return (long)(n+1)*n/2;
    }
}

看了一下解题发现不用专门去计算直接累加就行了:

java 复制代码
class Solution {
    public long countAlternatingSubarrays(int[] nums) {
        int len=nums.length;
        int count=1;
        long res=1L;
        for(int i=1;i<len;i++){
            if(nums[i]==nums[i-1]){
                count=1;
            }else{
                count++;
            }
            res+=count;
        }
        return res;
    }
}

加油!!!今天就到这了,有一块刷题可以一块啊,一起可以互相监督。

相关推荐
sheji34167 分钟前
【开题答辩全过程】以 基于springboot的房屋租赁系统的设计与实现为例,包含答辩的问题和答案
java·spring boot·后端
PiKaMouse.8 分钟前
navigation2-humble从零带读笔记第一篇:nav2_core
c++·算法·机器人
木井巳13 分钟前
【递归算法】子集
java·算法·leetcode·决策树·深度优先
lightqjx40 分钟前
【算法】二分算法
c++·算法·leetcode·二分算法·二分模板
行百里er1 小时前
优雅应对异常,从“try-catch堆砌”到“设计驱动”
java·后端·代码规范
ms_27_data_develop1 小时前
Java枚举类、异常、常用类
java·开发语言
xiaohe071 小时前
Spring Boot 各种事务操作实战(自动回滚、手动回滚、部分回滚)
java·数据库·spring boot
代码飞天2 小时前
wireshark的高级使用
android·java·wireshark
Wave8452 小时前
数据结构—树
数据结构