-
Notifications
You must be signed in to change notification settings - Fork 43
/
monotonic-array.py
131 lines (103 loc) · 2.91 KB
/
monotonic-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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
"""
896. Monotonic Array
Easy
An array is monotonic if it is either monotone increasing or monotone decreasing.
An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j].
Given an integer array nums, return true if the given array is monotonic, or false otherwise.
Example 1:
Input: nums = [1,2,2,3]
Output: true
Example 2:
Input: nums = [6,5,4,4]
Output: true
Example 3:
Input: nums = [1,3,2]
Output: false
Example 4:
Input: nums = [1,2,4,5]
Output: true
Example 5:
Input: nums = [1,1,1]
Output: true
Constraints:
1 <= nums.length <= 105
-105 <= nums[i] <= 105
"""
# V0
class Solution(object):
def isMonotonic(self, A):
"""
:type A: List[int]
:rtype: bool
"""
return self.isIncrease(A) or self.isDecrease(A)
def isIncrease(self, A):
for i in range(len(A) - 1):
if A[i] > A[i+1]:
return False
return True
def isDecrease(self, A):
for i in range(len(A) - 1):
if A[i] < A[i+1]:
return False
return True
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/82348997
# IDEA : CHECK IF THE ARRAY IS MONOTONIC ASCENDING OR MONOTONIC DESCENDING OR NOT
class Solution(object):
def isMonotonic(self, A):
"""
:type A: List[int]
:rtype: bool
"""
return self.isIncrease(A) or self.isDecrease(A)
def isIncrease(self, A):
return all(A[i] - A[i+1] >= 0 for i in range(len(A) - 1))
def isDecrease(self, A):
return all(A[i] - A[i+1] <= 0 for i in range(len(A) - 1))
# V1'
# https://zxi.mytechroad.com/blog/algorithms/array/leetcode-896-monotonic-array/
class Solution:
def isMonotonic(self, A):
inc = True;
dec = True;
for i in range(1, len(A)):
inc = inc and A[i] >= A[i - 1]
dec = dec and A[i] <= A[i - 1]
return inc or dec;
# V1''
# https://www.jiuzhang.com/solution/monotonic-array/#tag-highlight-lang-python
class Solution:
"""
@param A: a array
@return: is it monotonous
"""
def isMonotonic(self, A):
# Write your code here.
sign = None
for i in range(1, len(A)):
if(sign == None):
if(A[i] - A[i-1] > 0):
sign = 1
elif(A[i] - A[i-1] < 0):
sign = -1
else:
if((A[i] - A[i-1]) * sign < 0):
return False
return True
# V2
# Time: O(n)
# Space: O(1)
class Solution(object):
def isMonotonic(self, A):
"""
:type A: List[int]
:rtype: bool
"""
inc, dec = False, False
for i in range(len(A)-1):
if A[i] < A[i+1]:
inc = True
elif A[i] > A[i+1]:
dec = True
return not inc or not dec