LeetCode 969. Pancake Sorting【排序/数组】中等

该博客讨论了一种名为煎饼排序的数组排序算法,通过一系列的翻转操作将给定的整数数组排序。算法类似于冒泡排序,但每次找出当前未排序部分的最大值并翻转到正确位置。博客提供了C++实现,展示了在最坏情况下翻转次数不超过2*arr.length的高效性,并给出了实际运行时的性能指标。

Given an array of integers arr, sort the array by performing a series of pancake flips.

In one pancake flip we do the following steps:

  • Choose an integer k where 1 <= k <= arr.length.
  • Reverse the sub-array arr[0...k-1] (0-indexed).

For example, if arr = [3,2,1,4] and we performed a pancake flip choosing k = 3, we reverse the sub-array [3,2,1], so arr = [1,2,3,4] after the pancake flip at k = 3.

Return an array of the k-values corresponding to a sequence of pancake flips that sort arr. Any valid answer that sorts the array within 10 * arr.length flips will be judged as correct.

Example 1:

Input: arr = [3,2,4,1]
Output: [4,2,4,3]
Explanation: 
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
Starting state: arr = [3, 2, 4, 1]
After 1st flip (k = 4): arr = [1, 4, 2, 3]
After 2nd flip (k = 2): arr = [4, 1, 2, 3]
After 3rd flip (k = 4): arr = [3, 2, 1, 4]
After 4th flip (k = 3): arr = [1, 2, 3, 4], which is sorted. 

Example 2:

Input: arr = [1,2,3]
Output: []
Explanation: The input is already sorted, so there is no need to flip anything.
Note that other answers, such as [3, 3], would also be accepted.

Constraints:

  • 1 <= arr.length <= 100
  • 1 <= arr[i] <= arr.length
  • All integers in arr are unique (i.e. arr is a permutation of the integers from 1 to arr.length).

题意:给你一个整数数组 arr ,请使用 煎饼翻转 完成对数组的排序。一次煎饼翻转的执行过程如下:

  • 选择一个整数 k1 <= k <= arr.length
  • 反转子数组 arr[0...k-1]下标从 0 开始

以数组形式返回能使 arr 有序的煎饼翻转操作所对应的 k 值序列。任何将数组排序且翻转次数在 10 * arr.length 范围内的有效答案都将被判断为正确。


解法 排序

类似冒泡排序的思想,每次先找到剩余数组区间中的最大数组元素,然后通过翻转将其放置在区间末尾,直到整个数组都有序为止。这一做法的翻转次数最多为 2 * arr.length ,因为对每个最大数组元素,可能需要先翻转到数组首位,然后翻转到区间尾部。

class Solution {
public:
    vector<int> pancakeSort(vector<int>& arr) {
        vector<int> ans;
        for (int i = arr.size() - 1; i >= 0; --i) {
            int maxj = 0;
            for (int j = 1; j <= i; ++j) if (arr[j] > arr[maxj]) maxj = j;
            if (maxj == i) continue; //最大值在末尾
            ans.push_back(maxj + 1); //翻转arr[0,maxj]这一区间,将最大值翻转到数组首位
            reverse(arr.begin(), arr.begin() + maxj + 1);
            ans.push_back(i + 1); //翻转arr[0,i]这一区间,将最大值翻转到i位
            reverse(arr.begin(), arr.begin() + i + 1);
        }
        return ans;
    }
};

运行效率如下所示:

执行用时:4 ms, 在所有 C++ 提交中击败了78.95% 的用户
内存消耗:10.8 MB, 在所有 C++ 提交中击败了76.12% 的用户
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

memcpy0

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

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

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

打赏作者

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

抵扣说明:

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

余额充值