Check if Array Is Sorted and Rotated

Given an array num, 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 result in an array B of the same length such that A[i] == B[(i+x) % A.length], where % is the modulo operation.

Example:

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].

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

bool check(vector<int&nums)
{
    //find position of minimum element
    int k = min_element(nums.begin(), nums.end()) - nums.begin();

    //length of array
    int n = nums.size();

    int j;
    if (k == 0)
    {
        j = n - 1;
        while (j > 0 && nums[j] == nums[k])
        {
            j--;
        }
    }
    else
    {
        j = k - 1;
    }
    int i = k;
    while (i != j)
    {
        if (nums[i] > nums[(i + 1) % n])
        {
            return false;
        }
        i = (i + 1) % n;
    }
    return true;
}

int main()
{
    vector<intnums = {34512};

    if (check(nums))
        cout << "true";
    else
        cout << "false";

    return 0;
}


No comments:

Post a Comment