-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcount_hills_and_valleys_in_array.py
46 lines (38 loc) · 1.55 KB
/
count_hills_and_valleys_in_array.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
'''
You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j].
Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index.
Return the number of hills and valleys in nums.
'''
class Solution:
def countHillValley(self, nums: List[int]) -> int:
newnum = list()
for i in range(len(nums)):
if nums[i] == nums[i-1]:
continue
else:
newnum.append(nums[i])
print('after')
print(newnum)
nums = newnum
count = 0
i = 1
while i < len(nums)-1:
if nums[i] > nums[i-1] and nums[i] > nums[i+1]:
count += 1
if nums[i] < nums[i-1] and nums[i] < nums[i+1]:
count += 1
i += 1
print('total hill valey count', count)
return count
class Solution:
def countHillValley(self, nums: List[int]) -> int:
c = 0
i = 1
while i <len(nums)-1:
j = i+1
while j < len(nums)-1 and nums[j] == nums[i]:
j += 1
if (nums[i-1] > nums[i] and nums[j] > nums[i]) or (nums[i-1] < nums[i] and nums[j] < nums[i]):
c += 1
i = j
return c