feat(896-monotonic-array): better solution
This commit is contained in:
parent
1e76039c03
commit
a8ffbb4c5d
@ -1,16 +1,29 @@
|
|||||||
class Solution:
|
class Solution:
|
||||||
def isMonotonic(self, nums: List[int]) -> bool:
|
def isMonotonic(self, nums: List[int]) -> bool:
|
||||||
direction = 0
|
# Means difference between two nums indicate that it is
|
||||||
prev = nums[0]
|
# decreasing or that difference is 0
|
||||||
|
isNonIncreasing = True
|
||||||
|
|
||||||
for num in nums[1:]:
|
# Same idea as above butnopposite: it is either increasing
|
||||||
newDirection = num - prev
|
# or difference is 0
|
||||||
|
isNonDecreasing = True
|
||||||
|
|
||||||
if direction == 0:
|
for i in range(1, len(nums)):
|
||||||
direction = newDirection
|
difference = nums[i] - nums[i - 1]
|
||||||
elif direction < 0 < newDirection or direction > 0 > newDirection:
|
|
||||||
|
# We can say with confidence if this condition ever passes
|
||||||
|
# that sequence is increasing (e.g. 1 2 4 8 ...)
|
||||||
|
if difference > 0:
|
||||||
|
isNonIncreasing = False
|
||||||
|
# Sequence is decreasing (e.g. 1 0 -2 -4 ...)
|
||||||
|
elif difference < 0:
|
||||||
|
isNonDecreasing = False
|
||||||
|
|
||||||
|
# If both flags are set to False, that means there is no
|
||||||
|
# monotonous state and we can break early.
|
||||||
|
if not isNonIncreasing and not isNonDecreasing:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
prev = num
|
# At the end, if either flag remains True, we have a montonous
|
||||||
|
# array
|
||||||
return True
|
return isNonIncreasing or isNonDecreasing
|
||||||
|
Loading…
Reference in New Issue
Block a user