Huffuman树

364 阅读2分钟

解析: 这题主要用到的知识点是数组长度的变化,可以用静态数组,当数组长度变化后,重新创建一个新的数组来来存放数据;也可以使用动态数组,动态的添加和删除数据。

具体实现思路是:

  • 1、数组定义
  • 2、数组排序
  • 3、取出最小值并运算
  • 4、删除数组中指定的值
  • 5、向数组中添加新的数据
  • 6、判断数组的大小是否为1,如果不是则从第二个步骤重复

静态数组实现:

package _3_5_test;

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

import org.w3c.dom.css.ElementCSSInlineStyle;

/*Huffuman树
 * 1、数组定义
 * 2、数组排序
 * 3、取出最小值并运算
 * 4、删除数组中指定的值
 * 5、向数组中添加新的数据
 * 6、判断数组的大小是否为1,如果不是则从第二个步骤重复
 * */
public class FourtySeven {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scanner = new Scanner(System.in);

		int n = scanner.nextInt();

		int num[] = new int[n];

		for (int i = 0; i < n; i++) {
			num[i] = scanner.nextInt();
		}

		System.out.println(deal(num));

	}

	// 定义一个全局变量用于存放最终的结果
	public static int endSum;

	public static int deal(int a[]) {

		int num[] = a;
		// 创建一个新的长度的数组,用于存放新的数列
		int result[] = new int[num.length - 1];

		// 对数组按升序排序
		Arrays.sort(num);

		// 对数组中最小的两位数进行运算
		int sum = num[0] + num[1];

		// 存放最终的结果
		endSum += sum;

//		存放新的数列
		for (int i = 0; i < result.length - 1; i++) {
			result[i] = num[i + 2];
		}
		result[result.length - 1] = sum;

		if (result.length != 1) {
			return deal(result);
		}
		
		return endSum;

	}

}

动态数组实现:

package _3_5_test;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Scanner;

public class FourtySeven_Two {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner scanner = new Scanner(System.in);

		int n = scanner.nextInt();

		ArrayList arrayList = new ArrayList<>();

		for (int i = 0; i < n; i++) {
			arrayList.add(scanner.nextInt());
		}
		
//		存放最后的结果
		int result = 0;
		while (arrayList.size() != 1) {
			Collections.sort(arrayList);

			int sum = (int) arrayList.get(0) + (int) arrayList.get(1);

			arrayList.remove(0);
			arrayList.remove(0);
			arrayList.add(sum);

			result += (int) arrayList.get(arrayList.size() - 1);

		}

		System.out.println(result);

	}

}

通过对比可以发现动态数组因为不用反复创建对象,运行时间快了接近一倍