Fork me on GitHub

【数据结构】算法 Pancake Sorting 煎饼排序

Pancake Sorting 煎饼排序

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.

给定一数组,每次允许将前k个元素反转,按照这个策略,要通过几次k反转,使得最终的数组是有序的[从小到大]

输入:[3,2,4,1]
输出:[4,2,4,3]
解释:
我们执行 4 次煎饼翻转,k 值分别为 4,2,4,和 3。
初始状态 arr = [3, 2, 4, 1]
第一次翻转后(k = 4):arr = [1, 4, 2, 3]
第二次翻转后(k = 2):arr = [4, 1, 2, 3]
第三次翻转后(k = 4):arr = [3, 2, 1, 4]
第四次翻转后(k = 3):arr = [1, 2, 3, 4],此时已完成排序。 
 

思路

先将最大的数放到正确的位置即n,如果要达到目标,那么就首先要将其放到第一位,然后通过一次整组反转来实现,然后就是准备排剩下的n-1个。

public void reverse(int[] arr ,int n ,int[] ind){
        for (int i = 0,j=n-1; i <j ; i++,j--) {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            ind[arr[i]]=i;
            ind[arr[j]]=j;
        }
        return;
    }
    public List<Integer> pancakeSort(int[] arr) {
        int[] ind = new int[arr.length+1];    
        ArrayList<Integer> ret=new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            ind[arr[i]]=i;
        }
        for (int i = arr.length; i >=1; i--) {
            if(ind[i] ==i-1){
                //判断是否处于正确的位置
                continue;
            }
            if (ind[i]+1!=1){
                //本轮最大的待排数,还不处于第一位,需要反转前 ind[i]+1个
                ret.add(ind[i]+1);
                reverse(arr,ind[i]+1,ind);
            }
            if(i!=1){
                ret.add(i);
                reverse(arr,i,ind);
            }
        }
        return ret;
    }
posted @ 2021-04-11 10:31  WilliamCui  阅读(106)  评论(0编辑  收藏  举报