[数组中等题] LeetCode 969. 煎饼排序

LeetCode 969. 煎饼排序

https://leetcode.cn/problems/pancake-sorting/

将数组元素状态分为 “已排序元素” 和 “未排序元素”。
经过 (arr 数组长度 - 1) 次循环即可将 arr 数组排序完成,每次循环的目标是将 “未排序元素” 中的最大值通过反转,使其放在 “未排序元素” 的末尾,并将其置为 “已排序元素” 的状态。

定义 notSortedCount 为 “未排序元素” 的长度, 初始值为 arr 数组的长度。

  • 首先找到 “未排序元素” 中最大值。
  • 若该最大值已经在 “未排序元素” 的末尾, 继续下一次循环。
  • 否则, 先将该最大值反转到 “未排序元素” 的开头; 然后再反转数组 [0 ~ noSortedCount-1], 将最大值放在 “未排序元素” 的末尾。
  • 最后将该最大值置为 “已排序元素” 的状态,然后 notSortedCount--, 当 notSortedCount1 时, 排序完成。

举例
Input: arr = [3, 2, 4, 1]
Output: [3, 4, 2, 3, 2]

每轮反转的过程:
第一轮:[4, 2, 3, 1]
第二轮:[1, 3, 2, 4]
第三轮:[3, 1, 2, 4]
第四轮:[2, 1, 3, 4]
第五轮:[1, 2, 3, 4]

时间复杂度: O ( n 2 ) O(n^2) O(n2)
空间复杂度: O ( 1 ) O(1) O(1)

Solution

class Solution {
public:
    // 反转前 k 个数
    void reverseK(vector<int>& arr, int k) {
        int left = 0, right = k - 1;
        int t = 0;
        while (left < right) {
            t = arr[left];
            arr[left] = arr[right];
            arr[right] = t;
            left++;
            right--;
        }
    }
    
    vector<int> pancakeSort(vector<int>& arr) {
        vector<int> ans;
        int notSortedCount = arr.size(); 
        int maxIndex = 0;

        while (notSortedCount > 1) {
            maxIndex = 0;
            for (int i = 1; i < notSortedCount; ++i) {
                if (arr[i] > arr[maxIndex]) {
                    maxIndex = i;
                }
            }
            // 若 maxIndex 已经在 "未排序元素" 的末尾, 继续下一次循环
            if (maxIndex == notSortedCount - 1) {
                notSortedCount--;
                continue;
            }
            // 若最大值索引不为 0, 将 [0 ~ maxIndex] 元素反转, 使最大值移动到 "未排序元素" 的开头
            if (maxIndex != 0) {
                reverseK(arr, maxIndex + 1); 
                ans.emplace_back(maxIndex + 1);
            }
            // 将最大值反转到 "未排序元素" 的末尾
            reverseK(arr, notSortedCount);
            ans.emplace_back(notSortedCount);
            notSortedCount--;
        }
        return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哇咔咔负负得正

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值