- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmountain_array_longest.py
More file actions
Latest commit
42 lines (36 loc) · 1.26 KB
/
Copy pathmountain_array_longest.py
File metadata and controls
42 lines (36 loc) · 1.26 KB
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
"""
https://leetcode.com/problems/longest-mountain-in-array/solution/shu-zu-zhong-de-zui-chang-shan-mai-by-leetcode/
"""
importunittest
fromtypingimportList
# 先从左到右找到第一个山脉数组的上山点,然后再往后搜索
deflongest_mountain_in_array(nums: List[int]) ->int:
length=len(nums)
max_len=0
i=1
whilei<length:
ifnums[i] <=nums[i-1]:
i+=1
continue
# 下面这种写法也行,不过效率不如continue
# while i < length and nums[i] <= nums[i - 1]:
# i += 1
start=i-1
whilei<lengthandnums[i] >nums[i-1]:
i+=1
whilei<lengthandnums[i] <nums[i-1]:
i+=1
# 由于不知道何时到达边界,所以下坡时每遍历一次就计算一下最大值
max_len=max(max_len, i-start)
returnmax_len
classUnitTest(unittest.TestCase):
TEST_CASES= [
([7, 4, 8], 0),
([5, 4, 3, 2, 1], 0),
([0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0], 11),
([2, 2, 2], 0),
([2, 1, 4, 7, 3, 2, 5], 5),
]
deftesting(self):
fornums, expectedinself.TEST_CASES:
self.assertEqual(expected, longest_mountain_in_array(nums))