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

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

相关推荐
MartinYeung532 分钟前
[论文学习]DP2Unlearning:高效且具保证的大型语言模型遗忘框架(基于差分隐私的 LLM Unlearning 方法)
学习·算法·语言模型
Tian_Hang1 小时前
C++原型模式(Protype)
开发语言·c++·算法
bIo7lyA8v1 小时前
算法复杂度的渐进分析与实际运行时间的差异的技术8
算法
JAVA面经实录9171 小时前
操作系统(面试全覆盖)
java·计算机网络·面试
一切皆是因缘际会1 小时前
LLM轻量化联邦微调机理
数据结构·人工智能·数学建模·ai
编程的一拳超人2 小时前
Maven 国内高速镜像推荐(按速度排序)
java·maven
yuan199972 小时前
欧拉梁静力与屈曲计算的 MATLAB 实现(有限差分法 + 解析解)
开发语言·算法·matlab
云烟成雨TD2 小时前
Spring AI 1.x 系列【61】Spring AI 2.0 升级指南
java·人工智能·spring
玖玥拾2 小时前
C/C++ 数据结构(六)链表迭代器与底层
c语言·数据结构·c++·链表·stl库