华为面试题计算求和的最短时间问题
问题描述
问题分析
图解
我们以nums = {5,4,1,2,2}这5个数为例
代码实现
public static void main(String[] args) {
//编写输入案例:n为计算数的个数;n个数用队列queue接收(此处队列用添加有序的LinkedList定义)
Scanner scanner = new Scanner(System.in);
System.out.println("请输入要输入的计算的个数(n) :");
int n = scanner.nextInt();
System.out.println("请输入这" + n + "个数(正整数) :");
//定义一个队列(用链表去定义)
LinkedList<Integer> queue = new LinkedList<>();
for (int i = 0; i < n; i++) {
queue.add(scanner.nextInt());
}
CalculatorProblem solution = new CalculatorProblem();
//定义minTime作为最后输出的计算n个数花费的最短时间,初始化为0
int minTime = 0;
//定义计算最短时间的算法
while (queue.size() > 1) {
//首先我们要对该队列的数据进行排序:使用插入排序法
insertSort(queue);
//取出最小的两个数:即获取排序后的前两个数值:
int a = queue.removeFirst();
int b = queue.removeFirst();
int time = a + b;//计算a+b花费的时间
minTime = minTime + time;//更新此时进行计算花费的最短时间
queue.add(time);//然后将计算的和添加到队列中
}
//输出计算n个数花费的最短时间
System.out.println("计算这" + n + "个数花费的最短时间为 :" + minTime);
}
private static void insertSort(LinkedList<Integer> queue) {
int len = queue.size();
for (int j = 1; j < len; j++) {//默认0位置为有序表,1~len-1位无序表
int insert = queue.get(j);//获取无序表中的元素:即要准备插入的元素
int i = j - 1;//遍历j-1 ~ 0的位置,寻找insert在有序表中的插入位置
while (i >=0 && queue.get(i) > insert) {//只要前面的值比inset大,则将前面的值进行后移处理
int temp = queue.get(i);
queue.set(i + 1,temp);
i--;
}
//退出while循环,即找到了inset插入的位置
queue.set(i + 1,insert);
}
}