File tree 1 file changed +31
-0
lines changed
1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Time: O(n)
2
+ # Space: O(1)
3
+
4
+ # sliding window, two pointers
5
+ class Solution (object ):
6
+ def numberOfAlternatingGroups (self , colors ):
7
+ """
8
+ :type colors: List[int]
9
+ :rtype: int
10
+ """
11
+ k = 3
12
+ result = curr = left = 0
13
+ for right in xrange (len (colors )+ k - 1 ):
14
+ if right - left + 1 == k :
15
+ result += int (curr == k - 1 )
16
+ curr -= int (colors [left ] != colors [(left + 1 )% len (colors )])
17
+ left += 1
18
+ curr += int (colors [right % len (colors )] != colors [(right + 1 )% len (colors )])
19
+ return result
20
+
21
+
22
+ # Time: O(n)
23
+ # Space: O(1)
24
+ # sliding window
25
+ class Solution2 (object ):
26
+ def numberOfAlternatingGroups (self , colors ):
27
+ """
28
+ :type colors: List[int]
29
+ :rtype: int
30
+ """
31
+ return sum (colors [i ] != colors [(i + 1 )% len (colors )] != colors [(i + 2 )% len (colors )] for i in xrange (len (colors )))
You can’t perform that action at this time.
0 commit comments