2672. 有相同颜色的相邻元素数目

174 阅读1分钟

题目:
给你一个下标从 0 开始、长度为 n 的数组 nums 。一开始,所有元素都是 未染色 (值为 0 )的。

给你一个二维整数数组 queries ,其中 queries[i] = [indexi, colori] 。

对于每个操作,你需要将数组 nums 中下标为 indexi 的格子染色为 colori 。

请你返回一个长度与 queries 相等的数组 **answer **,其中 **answer[i]是前 i 个操作 之后 ,相邻元素颜色相同的数目。

更正式的,answer[i] 是执行完前 i 个操作后,0 <= j < n - 1 的下标 j 中,满足 nums[j] == nums[j + 1] 且 nums[j] != 0 的数目。
算法:
方法一:模拟
读懂题目,理清思路

func colorTheArray(n int, queries [][]int) []int {
    ans := make([]int, len(queries))
    count := 0
    indexColor := make(map[int]int, 0)
    for i := range queries {
        index, newColor := queries[i][0], queries[i][1]
        curColor, ok := indexColor[index]
        // 从没有颜色变为有颜色,curColor不为0
        if !ok {
            if 0 <= index - 1 && indexColor[index - 1] == newColor {
                count ++
            } 
            if index + 1 < n && indexColor[index + 1] == newColor {
                count ++
            } 
        // 将有颜色的改颜色 
        } else {
            // 抹掉颜色
            if 0 <= index - 1 && indexColor[index - 1] == curColor {
                count --
            } 
            if index + 1 < n && indexColor[index + 1] == curColor {
                count --
            } 
            // 新增颜色
            if 0 <= index - 1 && indexColor[index - 1] == newColor {
                count ++
            } 
            if index + 1 < n && indexColor[index + 1] == newColor {
                count ++
            } 
        }
        indexColor[index] = newColor
        ans[i] = count
    }
    return ans
}