-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy path904.py
59 lines (55 loc) · 1.96 KB
/
904.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
__________________________________________________________________________________________________
sample 692 ms submission
class Solution:
def totalFruit(self, tree: List[int]) -> int:
if not tree:
return 0
if len(set(tree)) <= 2:
return len(tree)
ans = size = cnt = 1
type1 = type2 = tree[0]
for fruit in tree[1:]:
if fruit == type1:
cnt += 1
else:
if fruit != type2:
ans = max(ans, size)
size = cnt
type1, type2 = fruit, type1
cnt = 1
size += 1
return max(ans, size)
__________________________________________________________________________________________________
sample 16884 kb submission
class Solution:
def totalFruit(self, tree: List[int]) -> int:
dic = {}
fruits=[]
fruit_point = {}
left, res = 0, 0
if len(tree) < 2:
return len(tree)
for i, fruit in enumerate(tree):
#print (dic, fruits)
if fruit not in dic:
dic[fruit] = 1
fruit_point[fruit] = i
else:
dic[fruit] += 1
fruit_point[fruit] = i
if len(dic) > 2:
#print(fruit_point)
temp = float('inf')
for key in fruit_point:
#print (key, fruit_point[key], temp)
if fruit_point[key] < temp:
temp = fruit_point[key]
first_key = key
first_pointer = fruit_point[key]
#print(first_key, first_pointer)
del fruit_point[first_key]
del dic[first_key]
left = first_pointer + 1
res = max(res, i - left + 1)
return res
__________________________________________________________________________________________________