力扣969煎饼翻转

力扣969:https://leetcode-cn.com/problems/pancake-sorting/

思路:将原数组和排好序的数组按位置(从后往前)进行比较,对应位置数值不同就进行翻转。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

class Solution {
    public static List<Integer> pancakeSort(int[] A) {
        List<Integer> list = new ArrayList<>();
        //声明一个数组存储原数组顺序
        int[] B = new int[A.length];
        for(int i = 0;i<A.length;i++) {
        	B[i] = A[i];
        }
        //对原数组进行排序
        Arrays.sort(A);
        //从后往前进行遍历原数组
        for(int i =A.length-1;i>=0;i--) {
        	//位置不匹配进行翻转
        	if(B[i]!=A[i]) {
        		int index = getMaxIndex(B,A[i]);
        		//翻转一次,翻转到首部
        		list.add(index+1);
        		B = reserve(B, index);
        		//翻转第二次,翻转到当前位置
        		list.add(i+1);
        		B = reserve(B, i);
        	}
        } 
        return list;
    }
    
    //找到要翻转得元素在原数组得位置。
    public static int getMaxIndex(int[] A,int max) {
    	for(int i = 0;i<A.length;i++) {
    		if(A[i] ==max) {
    			return i;
    		}
    	}
    	return -1;
    }
    
    
    
    public static int[] reserve(int[] A,int endIndex) {
    	LinkedList<Integer> stack = new LinkedList<>();
    	int[] B = new int[A.length];
    	for(int i = 0;i<=endIndex;i++) {
    		stack.push(A[i]);
    	}
    	for(int i = 0;i<=endIndex;i++) {
    		B[i] = stack.pop();
    	}
    	for(int i = endIndex+1;i<A.length;i++) {
    		B[i] = A[i];
    	}
    	
    	return B;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43695091/article/details/89817949