넘치게 채우기

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

PS/LeetCode

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

riveroverflow 2025. 2. 2. 10:17
728x90
반응형

https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/description/

leetcode - Check if Array Is Sorted and Rotated

문제 유형: 배열, 구현

문제 난이도: 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.

 

정수 배열 nums가 주어집니다. 만약에 정렬된 배열에서 회전이 일어난 배열이라면 true를, 아니면 false를 반환하시오.

 

풀이

nums[i] 번부터 시작해서, nums[(i+j+n)%n]을 순회하며 계속 비내림차순이면, (for i = 0 ... n-1, for j = 1 ... n-1) 정렬된 배열에서 회전이 일어난 배열이다.

 

코드

C++

class Solution {
public:
    bool check(vector<int>& nums) {
        int n = nums.size();
        for(int i = 0; i < n; ++i) {
            bool flag = true;
            int last = nums[i];
            for(int j = 1; j < n; ++j) {
                if(last > nums[(i+j+n)%n]) flag = false;
                last = nums[(i+j+n)%n];
            }
            if(flag) return true;
        }
        return false;
    }
};

 

 

Go

func check(nums []int) bool {
    n := len(nums)
    for i := 0; i < n; i++ {
        flag := true
        last := nums[i]
        for j := 1; j < n; j++ {
            if last > nums[(i+j+n)%n] {
                flag = false
                break
            }
            last = nums[(i+j+n)%n];
        }
        if flag {
            return true;
        }
    }

    return false;
}
728x90
반응형