这个题我一开始想着用Map类型,但是发现map类型没办法排序,于是各种尝试之后使用Book类+Comparable接口实现了这个功能。
题目链接如下:
图书排序
AC代码如下:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.*;
// 1:无需package
// 2: 类名必须Main, 不可修改
class Book implements Comparable{private Integer id;private Integer quan;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public Integer getQuan() {return quan;}public void setQuan(Integer quan) {this.quan = quan;}public Book(Integer id, Integer quan) {super();this.id = id;this.quan = quan;}@Overridepublic int compareTo(Object o) {// TODO Auto-generated method stubBook book = (Book)o;if (this.quan-book.quan>0) {return 1;}if (this.quan-book.quan==0) {return this.id.compareTo(book.id);}return -1;}}
public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int n = scanner.nextInt();TreeSet tSet = new TreeSet<>();for(int i=0;i<n;i++) {int id = scanner.nextInt();int quan = scanner.nextInt();tSet.add(new Book(id, quan));}Iterator iterator = tSet.iterator();while(iterator.hasNext()) {Book book = (Book) iterator.next();System.out.println(book.getId());}}
}