[LeetCode] 3206. Alternating Groups I

CNoodle發表於2024-11-26

There is a circle of red and blue tiles. You are given an array of integers colors. The color of tile i is represented by colors[i]:
colors[i] == 0 means that tile i is red.
colors[i] == 1 means that tile i is blue.
Every 3 contiguous tiles in the circle with alternating colors (the middle tile has a different color from its left and right tiles) is called an alternating group.

Return the number of alternating groups.

Note that since colors represents a circle, the first and the last tiles are considered to be next to each other.

Example 1:
Input: colors = [1,1,1]
Output: 0
Explanation:
Example 1

Example 2:
Input: colors = [0,1,0,0,1]
Output: 3
Explanation:
Example 2

Alternating groups:
Example 2
Example 2
Example 2

Constraints:
3 <= colors.length <= 100
0 <= colors[i] <= 1

交替組 I。

給你一個整數陣列 colors ,它表示一個由紅色和藍色瓷磚組成的環,第 i 塊瓷磚的顏色為 colors[i] :

colors[i] == 0 表示第 i 塊瓷磚的顏色是 紅色 。
colors[i] == 1 表示第 i 塊瓷磚的顏色是 藍色 。

環中連續 3 塊瓷磚的顏色如果是 交替 顏色(也就是說中間瓷磚的顏色與它 左邊 和 右邊 的顏色都不同),那麼它被稱為一個 交替 組。

請你返回 交替 組的數目。

注意 ,由於 colors 表示一個 環 ,第一塊 瓷磚和 最後一塊 瓷磚是相鄰的。

思路

這個題目其實是讓你看一個長度為 3 的視窗裡面元素的情況。不過這道題我們只需要考慮視窗內的 3 個元素是否是交替的即可。記得遍歷到最後的時候下標要取模。

複雜度

時間O(n)
空間O(1)

程式碼

Java實現

class Solution {
    int n;

    public int numberOfAlternatingGroups(int[] colors) {
        n = colors.length;
        int res = 0;
        for (int i = 0; i < n; i++) {
            if (helper(colors, i)) {
                res++;
            }
        }
        return res;
    }

    private boolean helper(int[] colors, int index) {
        int first = colors[index % n];
        int second = colors[(index + 1) % n];
        int third = colors[(index + 2) % n];
        if (first != second && second != third) {
            return true;
        }
        return false;
    }
}

相關文章