2025-02-18:交替组Ⅱ。用go语言,给定一个整数数组 colors 和一个整数 k,数组 colors 由红色和蓝色瓷砖

举报
福大大架构师每日一题 发表于 2025/02/18 17:23:00 2025/02/18
【摘要】 2025-02-18:交替组Ⅱ。用go语言,给定一个整数数组 colors 和一个整数 k,数组 colors 由红色和蓝色瓷砖组成。数组中的元素表示瓷砖的颜色:1.colors[i] == 0 表示第 i 块瓷砖为红色。2.colors[i] == 1 表示第 i 块瓷砖为蓝色。这组瓷砖形成一个环,意味着数组的首尾是相连的。若环中有 k 块连续的瓷砖颜色交替(即除了首尾两块外,任意中间的瓷...

2025-02-18:交替组Ⅱ。用go语言,给定一个整数数组 colors 和一个整数 k,数组 colors 由红色和蓝色瓷砖组成。数组中的元素表示瓷砖的颜色:

1.colors[i] == 0 表示第 i 块瓷砖为红色。

2.colors[i] == 1 表示第 i 块瓷砖为蓝色。

这组瓷砖形成一个环,意味着数组的首尾是相连的。若环中有 k 块连续的瓷砖颜色交替(即除了首尾两块外,任意中间的瓷砖颜色都与它两侧的颜色不同),则这 k 块瓷砖被称为一个交替组。

你的任务是计算并返回这样的交替组的数量。

3 <= colors.length <= 100000。

0 <= colors[i] <= 1。

3 <= k <= colors.length。

输入:colors = [0,1,0,0,1,0,1], k = 6。

输出:2。

答案2025-02-18:

chatgpt

题目来自leetcode3208。

大体步骤如下:

1.定义一个函数 numberOfAlternatingGroups(colors []int, k int),接收一个整数数组 colors 和一个整数 k

2.初始化变量 rescnt 为0和1。

3.循环遍历数组 colors

  • 从下标 -k+2 开始,直到数组末尾。

  • 检查当前瓷砖颜色和它前一块瓷砖颜色是否不同。

4.如果颜色不同,递增 cnt;否则,将 cnt 重置为1。

5.如果 cnt 大于等于 k,增加 res 的计数。

6.返回最终的 res 值。

总的时间复杂度为O(n),其中n为数组colors的长度;

总的额外空间复杂度为O(1),因为除了几个变量外,没有使用额外的空间。

Go完整代码如下:

package main

import "fmt"

func numberOfAlternatingGroups(colors []int, k int) int {
	n := len(colors)
	res, cnt := 0, 1
	for i := -k + 2; i < n; i++ {
		if colors[(i+n)%n] != colors[(i-1+n)%n] {
			cnt++
		} else {
			cnt = 1
		}
		if cnt >= k {
			res++
		}
	}
	return res
}

func main() {
	colors := []int{0, 1, 0, 0, 1, 0, 1}
	k := 6
	result := numberOfAlternatingGroups(colors, k)
	fmt.Println(result) // 输出 : 2
}

在这里插入图片描述

Rust完整代码如下:

fn number_of_alternating_groups(colors: Vec<i32>, k: i32) -> i32 {
    let n = colors.len();
    let mut res = 0;
    let mut cnt = 1;

    for i in -k + 2..n as i32 {
        if colors[(i + n as i32) as usize % n] != colors[(i - 1 + n as i32) as usize % n] {
            cnt += 1;
        } else {
            cnt = 1;
        }

        if cnt >= k {
            res += 1;
        }
    }

    return res;
}

fn main() {
    let colors = vec![0, 1, 0, 0, 1, 0, 1];
    let k = 6;
    let result = number_of_alternating_groups(colors, k);
    println!("输出 : {}", result); // 输出 : 2
}

在这里插入图片描述

Python完整代码如下:

# -*-coding:utf-8-*-

def number_of_alternating_groups(colors, k):
    n = len(colors)
    res = 0
    cnt = 1
    
    for i in range(-k + 2, n):
        if colors[(i + n) % n] != colors[(i - 1 + n) % n]:
            cnt += 1
        else:
            cnt = 1
            
        if cnt >= k:
            res += 1
            
    return res

if __name__ == '__main__':
    colors = [0, 1, 0, 0, 1, 0, 1]
    k = 6
    result = number_of_alternating_groups(colors, k)
    print(result)  # 输出: 2

在这里插入图片描述

【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。