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

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

相关推荐
致Great21 小时前
Pi 的上下文压缩,到底是怎么工作的?
算法
St_rive21 小时前
Page Object设计模式
java·开发语言·设计模式
wuyk5551 天前
4.树:一对多的层次数据结构
开发语言·数据结构·stm32·单片机
watersink1 天前
机器学习聚类算法
算法·机器学习·聚类
风流 少年1 天前
Spring AI 2.0:SSE
java·人工智能·spring
凤山老林1 天前
精细化流量治理:Spring Boot 动态特性开关与灰度发布体系
java·spring boot·后端
luj_17681 天前
桥牌思维启示:系统设计的模块化架构
c语言·开发语言·c++·经验分享·算法
饼饼学习空间智能1 天前
家庭服务机器人训练数据怎么积累?仿真、真实采集与持续学习的技术路线分析
人工智能·算法·机器学习
Aphelios3801 天前
一次锁内网络IO引发的Tomcat线程池“饿死”事故
java·开发语言·spring boot·elasticsearch·tomcat·网络io阻塞·线程池耗尽