LeetCode——1752. Check if Array Is Sorted and Rotated [Simple]——Analysis and Code (Java)

LeetCode——1752. Check if Array Is Sorted and Rotated [Check if Array Is Sorted and Rotated][Simple]——Analysis and Code [Java]

1. Topic

Give you an array of nums. In the source array of nums, all elements are the same as nums, but arranged in non-decreasing order.
If nums can be obtained by rotating several positions (including 0 positions) of the source array, return true; otherwise, return false.
There may be duplicates in the source array.
Note: We call array A to get array B of the same length after rotating x positions, when they satisfy A[i] == B[(i+x)% A.length], where% is the remainder operation.

Example 1:

输入:nums = [3,4,5,1,2]
输出:true
解释:[1,2,3,4,5] 为有序的源数组。
可以轮转 x = 3 个位置,使新数组从值为 3 的元素开始:[3,4,5,1,2] 。

Example 2:

输入:nums = [2,1,3,4]
输出:false
解释:源数组无法经轮转得到 nums 。

Example 3:

输入:nums = [1,2,3]
输出:true
解释:[1,2,3] 为有序的源数组。
可以轮转 x = 0 个位置(即不轮转)得到 nums 。

Example 4:

输入:nums = [1,1,1]
输出:true
解释:[1,1,1] 为有序的源数组。
轮转任意个位置都可以得到 nums 。

Example 5:

输入:nums = [2,1]
输出:true
解释:[1,2] 为有序的源数组。
可以轮转 x = 5 个位置,使新数组从值为 2 的元素开始:[2,1] 。

prompt:

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

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/check-if-array-is-sorted-and-rotated
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, analysis and code

1. Direct marking

(1) Thinking

According to the meaning of the question, the array can only be obtained from the original ordinal array through at most one rotation, and a marker can be designed to assist in the judgment during the traversal process.

(2) Code

class Solution {
    
    
    public boolean check(int[] nums) {
    
    
        int len = nums.length;
        boolean firstArr = true;//标记是否已经过轮转
        for (int i = 1; i < len; i++) {
    
    
            if (nums[i] < nums[i - 1]) {
    
    
                if (firstArr == false)//需第二次轮转,不符合
                    return false;
                firstArr = false;
            }
        }
        if (firstArr == false && nums[len - 1] > nums[0])//轮转后首尾端连接时无法满足非递减
            return false;
        return true;
    }
}

(3) Results

Execution time: 0 ms, beating 100.00% of users
in all Java submissions ; memory consumption: 35.7 MB, beating 99.08% of users in all Java submissions.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/114043354