래원

[LeetCode] 1752. Check if Array Is Sorted and Rotated (Python) 본문

알고리즘/LeetCode

[LeetCode] 1752. Check if Array Is Sorted and Rotated (Python)

Laewon Jeong 2025. 2. 2. 20:31

 

난이도: Easy

문제 설명


Given an array nums, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false.

 

There may be duplicates in the original array.

 

Note: An array A rotated by x positions results in an array B of the same length such that A[i] == B[(i+x) % A.length], where % is the modulo operation.

 

문제 예제


Example 1:

Input: nums = [3,4,5,1,2]
Output: true
Explanation: [1,2,3,4,5] is the original sorted array.
You can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2].

Example 2:

Input: nums = [2,1,3,4]
Output: false
Explanation: There is no sorted array once rotated that can make nums.

Example 3:

Input: nums = [1,2,3]
Output: true
Explanation: [1,2,3] is the original sorted array.
You can rotate the array by x = 0 positions (i.e. no rotation) to make nums.

 

제한 사항


  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100

 

✏️ Solution(솔루션)


class Solution:
    def check(self, nums: List[int]) -> bool:
        sorted_nums = sorted(nums)
        n = len(nums)

        for i in range(n):
            check = 0
            for j in range(n):
                if nums[(j+i) % n] == sorted_nums[j]:
                    check += 1
                
            if check == n:
                return True
        
        return False

 

BruteForce 방식으로 해결했다.

 

결국 rotation은 nums의 길이 밖에 되지 않기 때문에 nums의 길이만큼 모두 로테이션을 돌려보았다.

이 때, 정렬한 nums와 같은 경우가 있다고 하면 True를 return하였다.

 

모든 경우를 확인해도 만족하지 않는다면 마지막에 False를 return 하였다.


문제: 1752. Check if Array Is Sorted and Rotated

 

깃허브: github

 

algorithmPractice/LeetCode/1878-check-if-array-is-sorted-and-rotated at main · laewonJeong/algorithmPractice

하루 한 문제 챌린지. Contribute to laewonJeong/algorithmPractice development by creating an account on GitHub.

github.com