答案其实都有,我来分享一些我发现的知识点。
第一种:(vector排序的写法)
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int N=sc.nextInt();
int sum=0;
Vector<Integer> buluo =new Vector<Integer>();
for(int i=0;i<N;i++) {
buluo.addElement(sc.nextInt());
}
while(buluo.size()>1) {
buluo.sort(new Comparator<Integer>() {
@Override
public int compare(Integer a,Integer b) {
return a - b;
}
});
int a =buluo.get(0)+buluo.get(1);
sum+=a;
buluo.remove(0);
buluo.remove(0);
buluo.addElement(a);
}
System.out.println(sum);
}
}
下面是在使用sort来排序vector的时候的提示,这说明我们需要在sort里面对comparator进行创建并且定义它,以便排序。
其中我们在对vector进行排序的时候,这个a-b的意思是指对其进行升序排序,前提是先定义形参a后定义形参b。当然反之,便是降序。
第二种:(priorityqueue排序的写法)
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int N=sc.nextInt();
int sum=0;
PriorityQueue<Integer> q =new PriorityQueue<>();
for(int i=0;i<N ;i++) {
q.add(sc.nextInt());
}
while(q.size()>1) {
int temp =q.poll();
temp+=q.poll();
sum+=temp;
q.add(temp);
}
System.out.println(sum);
}
}
priorityqueue为优先队列,默认为升序排列(会自动排序),如果想改为降序排列,则可以看下面我调试的代码:
import java.util.*;
class mycomparator implements Comparator<Integer>{
@Override
public int compare(Integer a,Integer b) {
return b-a;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int N=sc.nextInt();
int sum=0;
Comparator<Integer> mc =new mycomparator();
PriorityQueue<Integer> q =new PriorityQueue<>(mc);
for(int i=0;i<N ;i++) {
q.add(sc.nextInt());
}
while(q.size()>0) {
System.out.println(q.poll());
}
}
}
调试:
下面是优先序列的常用方法:
1.peek() 返回队首元素
2.poll() 返回队首元素,队首元素出队列
3.add() 添加元素
4.size() 返回队列元素个数
5.isEmpty() 判断队列是否为空,为空返回true,不空返回false