일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- DP
- 그래프
- 코딩테스트
- 하둡
- 리트코드
- Apache Hadoop
- 분산처리
- programmers
- leetcode
- docker
- 아파치 하둡
- 도커
- 쿠버네티스
- 이진탐색
- 파이썬
- String
- 알고리즘
- heapq
- Apache Spark
- 우선순위큐
- apache kafka
- Python
- Kubernetes
- BFS
- 오블완
- 아파치 카프카
- 분산
- 프로그래머스
- 아파치 스파크
- 티스토리챌린지
- Today
- Total
래원
[LeetCode] 1752. Check if Array Is Sorted and Rotated (Python) 본문
[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
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 1790. Check if One String Swap Can Make Strings Equal (Python) (0) | 2025.02.05 |
---|---|
[LeetCode] 3105. Longest Strictly Increasing or Strictly Decreasing Subarray (Python) (0) | 2025.02.03 |
[LeetCode] 3151. Special Array I (Python) (0) | 2025.02.01 |
[LeetCode] 827. Making A Large Island (Python) (0) | 2025.01.31 |
[LeetCode] 785. Is Graph Bipartite? (Python) (0) | 2025.01.30 |