Leetcode 刷题 Sort

969. Pancake Sorting

找到一个排序规则即可

  • 先找到最大的元素,将其反转到第一的位置。
  • 再将第一的位置反转到最后一个位置
  • 依次类推

每次都是经过 2*A.length 次操作

class Solution {
    
    public int findBiggest(int[] A, int end){
        int Maxx = -1;
        int index = -1;
        for(int i=0; i<=end; i++){
            if(Maxx < A[i]){
                index = i;
                Maxx = A[i];
            }
        }
        return index;
    }
    
    public void Reverse(int[] A, int end){
        int left = 0;
        int right = end;
        int change = 0;
        while(left < right){
            change = A[left];
            A[left] = A[right];
            A[right] = change;
            left++;
            right--;
        }
    }
    
    public List<Integer> pancakeSort(int[] A) {
        LinkedList<Integer> list = new LinkedList<Integer>();
        
        for(int i=A.length-1; i>=0; i--){
            int index = findBiggest(A, i);
            Reverse(A, index);
            Reverse(A, i);
            list.offerLast(index+1);
            list.offerLast(i+1);
        }
        return list;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值