|
| 1 | +# 1752. Check if Array Is Sorted and Rotated |
| 2 | + |
| 3 | +Given an array `nums`, return `true` if the array was originally sorted in non-decreasing order, |
| 4 | +then rotated some number of positions (including zero). Otherwise, return `false`. |
| 5 | + |
| 6 | +There may be duplicates in the original array. |
| 7 | + |
| 8 | +Note: An array `A` rotated by `x` positions results in an array `B` of the same length such that |
| 9 | +`A[i] == B[(i+x) % A.length]`, where `%` is the modulo operation. |
| 10 | + |
| 11 | +## 基礎思路 |
| 12 | + |
| 13 | +我們可以分解這題的思維,可以切分成以下幾個 Case: |
| 14 | +- Case 1: 陣列長度為 1,直接回傳 `True` |
| 15 | +- Case 2: 陣列長度大於 1,但是已經排序過,直接回傳 `True` |
| 16 | +- Case 3: 陣列長度大於 1,且沒有排序過,我們可以透過以下步驟來判斷: |
| 17 | + - 用個 Flag 紀錄陣列發生 Decreasing。 |
| 18 | + - 當發生第二次 Decreasing 時,直接回傳 `False` |
| 19 | + - 否則,檢查陣列最後一個元素是否小於第一個元素 (這樣就能把後半段的陣列接到前半段,形成排序過的陣列) |
| 20 | + |
| 21 | +這樣就能獲得高效率的解法。 |
| 22 | + |
| 23 | +## 解題步驟 |
| 24 | + |
| 25 | +### Step 1: 紀錄陣列長度並檢查是否長度為 1 |
| 26 | + |
| 27 | +```typescript |
| 28 | +const n = nums.length; |
| 29 | + |
| 30 | +// If the array is only one element, it is sorted. |
| 31 | +if (n === 1) { |
| 32 | + return true; |
| 33 | +} |
| 34 | +``` |
| 35 | + |
| 36 | +### Step 2: 檢查 Decreasing 順帶檢查是否排序過 |
| 37 | + |
| 38 | +```typescript |
| 39 | +let findDecreasing = false; |
| 40 | + |
| 41 | +for (let i = 1; i < n; i++) { |
| 42 | + // 如果當前元素大於前一個元素,則陣列沒有排序過。 |
| 43 | + if (nums[i] < nums[i - 1]) { |
| 44 | + // 當它發生第二次時,它不能被旋轉。 |
| 45 | + if (findDecreasing) { |
| 46 | + return false; |
| 47 | + } |
| 48 | + |
| 49 | + findDecreasing = true; |
| 50 | + } |
| 51 | +} |
| 52 | +``` |
| 53 | + |
| 54 | +### Step 3: 檢查是否排序過 |
| 55 | + |
| 56 | +```typescript |
| 57 | +// 如果陣列沒有排序過,則直接回傳 True |
| 58 | +if (!findDecreasing) { |
| 59 | + return true; |
| 60 | +} |
| 61 | +``` |
| 62 | + |
| 63 | +### Step 4: 檢查是否可以 Rotate |
| 64 | + |
| 65 | +```typescript |
| 66 | +// 如果陣列未被排序,且 Decreasing 只發生一次,則檢查是否可以 Rotate |
| 67 | +// 如果最後一個元素小於第一個元素,則可以 Rotate |
| 68 | +return nums[0] >= nums[n - 1]; |
| 69 | +``` |
| 70 | + |
| 71 | + |
| 72 | +## 時間複雜度 |
| 73 | +- 需要遍歷整個陣列,時間複雜度為 $O(n)$ |
| 74 | +- 總時間複雜度為 $O(n)$ |
| 75 | + |
| 76 | +> $O(n)$ |
| 77 | +
|
| 78 | +## 空間複雜度 |
| 79 | +- 只需要固定的常數旗標,空間複雜度為 $O(1)$ |
| 80 | + |
| 81 | +> $O(1)$ |
0 commit comments