본문 바로가기
Algorithm/LeetCode

[LeetCode] 896 | Monotonic Array

by 밤초록 2023. 3. 29.
896 | Monotonic Array
https://leetcode.com/problems/monotonic-array

 

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

 

Constraints:

  • 1 <= nums.length <= 105
  • -105 <= nums[i] <= 105

 

 

작성 코드

 

 

class Solution:
    def isMonotonic(self, nums: List[int]) -> bool:
        asc = True
        if nums[0] > nums[-1]:
            asc = False
        for i in range(len(nums) - 1):
            if ((nums[i] < nums[i + 1])  != asc) and (nums[i] != nums[i + 1]):
                return False
        return True

 

  • if 문 많이 안 쓰고 변수 하나만 저장해서 어찌저찌 하고 싶었음
  • 처음 값이 마지막 값보다 크다면 asc = False (Bool 형), 작거나 같다면 True
  • nums[i] < nums[i+1] != asc  --> 값이 큰가? 라는 Bool 형과 asc 값이 다르고, 값이 같지 않다면 False return
  • 값이 커지고     asc = True 일 때 True True 이므로 통과
  • 값이 작아지고 asc = True 일 때 False True 이므로 통과 X
  • 값이 커지고    asc  = False 일 때 True False 이므로 통과 X 
  • 없다면 True return

 

 

추가 코드

 

def isMonotonic(self, nums: List[int]) -> bool:
	return nums == sorted(nums) or nums == sorted(nums, reverse=True)
반응형

댓글