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;
    }
}

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

相关推荐
YuTaoShao3 分钟前
【LeetCode 每日一题】3013. 将数组分成最小总代价的子数组 II
算法·leetcode·职场和发展
serve the people5 分钟前
python环境搭建 (五) Dockerfile 和 docker-compose.yml 核心作用
java·python·docker
独断万古他化12 分钟前
【Spring 事务】核心概念与实战:从手动控制到注解自动事务
java·spring·事务
爱尔兰极光13 分钟前
LeetCode 热题 100--字母异位词分组
算法·leetcode·职场和发展
马猴烧酒.14 分钟前
【团队空间|第十一天】基础功能实现,RBAC权限控制,ShardingSphere详解
java·开发语言·数据库
fengxin_rou15 分钟前
从 String 到 Zset:Redis 核心数据结构全解析及排行榜应用
java·开发语言·redis·多线程
世界尽头与你16 分钟前
CVE-2025-55752_ Apache Tomcat 安全漏洞
java·安全·网络安全·渗透测试·tomcat·apache
Re.不晚16 分钟前
Java进阶之路--线程最最详细讲解
java·开发语言
EnglishJun16 分钟前
数据结构的学习(三)---双向链表与循环链表
数据结构·学习·链表
梵刹古音17 分钟前
【C语言】 数组基础与地址运算
c语言·开发语言·算法