排序是一种很频繁的计算任务。一个实际的例子是,当我们给某项竞赛的优胜者按金银铜牌排序的时候。在这个任务中可能的值只有三种1,2和3。我们用交换的方法把他排成升序的。
写一个程序计算出,计算出的一个包括1、2、3三种值的数字序列,排成升序所需的最少交换次数。
输入第1行为类别的数量N(1≤N≤1000)
输入第2行到第N+1行,每行包括一个数字(1或2或3)。
输出包含一行,为排成升序所需的最少交换次数。
样例输入
9 2 2 1 3 3 3 2 3 1
样例输出
4
package demo30; import java.util.Scanner; public class Main { private static int[] a = new int[1001]; private static int [] count = new int[4]; private static int num1 = 0;//表示为1的地方不是1的个数 private static int num2 = 0;//表示为2的地方是3的个数 private static int num3 = 0;//表示为3的地方是2的个数 public static void main(String[] args) { Scanner input = new Scanner(System.in); int count1 = 0; int n = input.nextInt(); for (int i = 1;i<=n;i++) { a[i] = input.nextInt(); count[a[i]]++; } for (int i = 1;i<=count[1];i++) { if (a[i] != 1) { num1++; } } for (int i = count[1] + 1; i <= count[1] + count[2]; ++i) { if (a[i] == 3){ num2++; } } for (int i = count[1] + count[2] + 1; i <= n; ++i){ if (a[i] == 2){ ++num3; } } int max = Integer.MAX_VALUE; if (num2 > num3) max = num2; else max = num3; count1 = num1+max; System.out.println(count1); } }