-
Notifications
You must be signed in to change notification settings - Fork 17
/
split-array-into-consecutive-subsequences.py
69 lines (61 loc) · 2.36 KB
/
split-array-into-consecutive-subsequences.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import heapq
from collections import defaultdict
from itertools import chain
from typing import Counter, DefaultDict, Dict, List, Tuple
class Solution:
def isPossible(self, nums: List[int]) -> bool:
counter1: Counter[int] = Counter()
counter2: Counter[int] = Counter()
counter3: Counter[int] = Counter()
for num in nums:
if counter1[num - 1] > 0:
counter1[num - 1] -= 1
counter2[num] += 1
elif counter2[num - 1] > 0:
counter2[num - 1] -= 1
counter3[num] += 1
elif counter3[num - 1] > 0:
counter3[num - 1] -= 1
counter3[num] += 1
else:
counter1[num] += 1
return all(count == 0 for count in counter1.values()) and all(
count == 0 for count in counter2.values()
)
def isPossibleBruteForce(self, nums: List[int]) -> bool:
ptrs: List[int] = list(range(len(nums)))
counts: List[int] = [1] * len(nums)
for pos in range(len(nums)):
for prev_pos in range(pos):
if (
nums[pos] == nums[prev_pos] + 1
and ptrs[prev_pos] == prev_pos
and counts[prev_pos] == 1
):
ptrs[prev_pos] = pos
counts[pos] += counts[prev_pos]
break
else:
for prev_pos in range(pos):
if (
nums[pos] == nums[prev_pos] + 1
and ptrs[prev_pos] == prev_pos
and counts[prev_pos] == 2
):
ptrs[prev_pos] = pos
counts[pos] += counts[prev_pos]
break
else:
for prev_pos in range(pos):
if (
nums[pos] == nums[prev_pos] + 1
and ptrs[prev_pos] == prev_pos
and counts[prev_pos] > 2
):
ptrs[prev_pos] = pos
counts[pos] += counts[prev_pos]
break
for pos in range(len(nums)):
if ptrs[pos] == pos and counts[pos] < 3:
return False
return True