疯狂队列

    xiaoxiao2022-07-12  139

    import java.util.Arrays; import java.util.LinkedList; import java.util.Scanner; public class Main7 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] h = new int[n]; for(int i = 0; i < h.length; i++) { h[i] = sc.nextInt(); } // 先进行排序 Arrays.sort(h); // 定义一个队列 LinkedList<Integer> queue = new LinkedList<>(); for(int i = 0; i < n/2; i++) { // 将最大的放中间,最小的放最大的左边,次小的放最大的右边 if(i == 0) { queue.addFirst(h[n-1-i]); queue.addFirst(h[i]); queue.addLast(h[i+1]); } // 次大的放次小的左边,再次的放队尾 else if(i % 2 !=0 ) { queue.addFirst(h[n-1-i]); queue.addLast(h[n-2-i]); } // 根据以上规律依次进行 else { queue.addFirst(h[i]); queue.addLast(h[i+1]); } } // 队尾两个相等,队尾与队首不相等时,将队尾放到队首 if(queue.get(n-1).equals(queue.get(n-2)) && !queue.get(n-1).equals(queue.get(0)) ) { queue.addFirst(queue.pollLast()); } // 队首两个相等,队尾和队首不相等时,将队首放到队尾 if(queue.get(0).equals(queue.get(1)) && !queue.get(n-1).equals(queue.get(0)) ) { queue.addLast(queue.pollFirst()); } System.out.println(queue); int sum = 0; for(int i = 0; i < n-1; i++) sum += Math.abs(queue.pollFirst() - queue.getFirst()); System.out.println(sum); } }

     

    最新回复(0)