【2020.10.14 广联达java笔试】跳舞机、元素平衡(27%)、一种排序

package top.actim.test09;

import java.util.Arrays;
import java.util.Scanner;

public class GLD {
    
    

	static Scanner sc = new Scanner(System.in);

	public static void main(String[] args) {
    
    
		// dance();
		// eleBalance();
		sort();
	}

	/**
	 * 有一种排序算法定义如下,该排序算法每次把一个元素提到序列的开头,例如2, 1, 3, 4,只需要一次操作把1提到序列起始位置就可以使得原序列从小到大有序。
	 * 现在给你个乱序的1-n的排列,请你计算最少需要多少次操作才可以使得原序列从小到大有序。
	 */
	static void sort() {
    
    
		// 输入第一行包含两个正整数n,表示序列的长度。(1 <= n <= 100000)接下来一行有n个正整数,表示序列中的n个元素,中间用空格隔开。
		// (1 <=a_i <= n)
		// 输出仅包含一个整数,表示最少的操作次数。
		// 样例输入:
		//		4
		//		2 1 3 4
		// 样例输出:
		//		1
		int n = sc.nextInt();
		int[] temp = new int[n];
		int[] targ = new int[n];
		for (int i = 0; i < temp.length; i++) {
    
    
			temp[i] = sc.nextInt();
			targ[i] = temp[i];
		}

		Arrays.sort(targ);

		int p = n - 1;
		int q = n - 1;

		while (p >= 0 && q >= 0) {
    
    
			if (temp[p] == targ[q]) {
    
    
				p--;
				q--;
			} else {
    
    
				while (p >= 0 && temp[p] != targ[q]) {
    
    
					p--;
				}
			}
		}

		System.out.println(q + 1);

	}

	/**
	 * 元素平衡,任意两种元素可合成一种其他元素,输入四种元素,输出平衡后最大元素总和,若无法平衡则-1
	 * 输入:1 2 2 4
	 * 输出:8
	 */
	static void eleBalance() {
    
    
		int[] ele = {
    
     sc.nextInt(), sc.nextInt(), sc.nextInt(), sc.nextInt() };
//		Arrays.sort(ele);
		int avg = (ele[0] + ele[1] + ele[2] + ele[3]) / 4;

		int sub = 0;

		int p = 0, q = avg;

		while (p <= q) {
    
    
			int i = (p + q) / 2;
			// System.out.println(i);

			sub = 0;
			for (int j = 0; j < ele.length; j++) {
    
    
				if (ele[j] > i) {
    
    
					sub += ele[j] - i;
				}
			}

			int count = 0;
			for (int j = 0; j < ele.length; j++) {
    
    
				if (ele[j] < i) {
    
    
					count += (i - ele[j]) * 2;
				}
			}

			if (sub == count) {
    
    
				System.out.println(i * 4);
				return;
			} else if (sub > count) {
    
    
				// System.out.println("P");
				p = i + 1;
			} else {
    
    
				q = i - 1;
			}
		}

		System.out.println(-1);
		return;

	}

	/**
	 * 正确+20,错误-10,不为负数
	 */
	static void dance() {
    
    
		char[] tar = sc.nextLine().toCharArray();
		char[] min = sc.nextLine().toCharArray();

		int con = 0;

		for (int i = 0; i < tar.length; i++) {
    
    
			if (tar[i] == min[i]) {
    
    
				con += 20;
			} else {
    
    
				con -= 10;
				con = con < 0 ? 0 : con;
			}
		}

		System.out.println(con);
	}

}

猜你喜欢

转载自blog.csdn.net/Activity_Time/article/details/109086342
今日推荐