9/21 每日一題(檢查是否為遞增或遞減)
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
class Solution:
def isMonotonic(self, nums: List[int]) -> bool:
a=0
b=0
c=0
old=nums[0]
for i in nums[1:]:
if i > old:
a=1
if i < old:
b=1
if i==old:
'相等'
c+=1
old=i
if c==len(nums)-1:
return True
if a == b :
return False
else:
return True
--------------------------
class Solution:
def isMonotonic(self, nums: List[int]) -> bool:
if len(nums) == 1:
return True
currVal = nums[0]
desc = False
incr = False
for i in nums:
if i < currVal:
desc = True
if i > currVal:
incr = True
if incr and desc:
return False
currVal = i
return True 標籤: leetcode

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁