疯狂队列

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);
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值