题目描述:
题目链接:https://leetcode.cn/problems/alternating-groups-ii/description/?envType=daily-question&envId=2024-11-27
思路一:暴力解法(超时)
遍历对每一个元素与其后面K-1个元素组成的K个元素均判断是否满足条件,若满足条件res+1
。
class Solution {
public:int numberOfAlternatingGroups(vector<int>& colors, int k) {int res = 0;int n = colors.size();for(int i=0; i<n; i++){int temp = colors[i];bool flag = true;for(int j=1; j<k ; j++){if(colors[(i+j)%n] == temp){flag = false;break;}temp = colors[(i+j)%n];}if(flag){res += 1;}}return res;}
};
思路二:
解题思路:
代码实现:
class Solution {
public:int numberOfAlternatingGroups(vector<int>& colors, int k) {int n = colors.size();int res = 0;int temp = 1;for(int i=-k+1; i<n-1; i++){if(colors[(i+n)%n] != colors[(i+n+1)%n]){temp+=1;}else{temp=1;}if(temp>=k){res+=1;}}return res;}
};