DAY 45 LeetCode学习笔记

969. 煎饼排序

前言

今天的排序思想,是每次找到最大值索引,将他翻转到最前面,再翻转到最后面,每一轮的翻转就逼近最终答案,由于答案不唯一,可以有不同的翻转方案。

题目

官方题目

源码

在这里插入图片描述

class Solution {
    public List<Integer> pancakeSort(int[] arr) {
        List<Integer> ans=new ArrayList<>();
        int index=arr.length-1;
        while(index>=0){
            int maxIndex=findMaxIndex(arr,index);
            if(maxIndex!=index){
                // 找到最大的索引,放到最前
                ans.add(maxIndex+1);
                pancake(arr,maxIndex+1);
                // 再放到最后
                ans.add(index+1);
                pancake(arr,index+1);
            }
            index--;

        }
        // 以下两部是剔除无用的翻转,但是其实不做也行(毕竟答案不唯一)
        // while(ans.contains(new Integer(1))){
        //     ans.remove(new Integer(1));
        // }
        // while(ans.contains(new Integer(0))){
        //     ans.remove(new Integer(0));
        // }
        return ans;

    }

    public static int findMaxIndex(int[]arr,int right){
        // 找到最大索引
        int max=0;
        int maxIndex=0;
        for(int i=0;i<=right;i++){
            if(arr[i]>max){
                max=arr[i];
                maxIndex=i;

            }
        }
        return maxIndex;

    }
    public static void pancake(int arr[],int count){
        // 煎饼反转,交换位置
        int left=0;
        int right=count-1;
        while(left<right){
            int tmp=arr[left];
            arr[left]=arr[right];
            arr[right]=tmp;
            left++;
            right--;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值