蓝桥杯每日一题-图书排序

这个题我一开始想着用Map类型,但是发现map类型没办法排序,于是各种尝试之后使用Book类+Comparable接口实现了这个功能。

题目链接如下:
图书排序

AC代码如下:

java 复制代码
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;
	}
	@Override
	public int compareTo(Object o) {
		// TODO Auto-generated method stub
		Book 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());
		}
	}
}
相关推荐
兆子龙9 小时前
ahooks useRequest 深度解析:一个 Hook 搞定所有请求
java·javascript
兆子龙9 小时前
React Suspense 从入门到实战:让异步加载更优雅
java·javascript
咕白m62512 小时前
Java 实现 Excel 转 HTML:完整示例
java
RealPluto12 小时前
Spring AOP 失效排查
java·spring
码路飞13 小时前
热榜全是 OpenClaw,但我用 50 行 Python 就造了个桌面 AI Agent 🤖
java·javascript
Nyarlathotep011313 小时前
LinkedList源码分析
java·后端
CoovallyAIHub13 小时前
181小时视频丢给GPT-5,准确率只有15%——南大联合NVIDIA等五校发布多模态终身理解数据集
深度学习·算法·计算机视觉
用户83071968408213 小时前
Java 告别繁琐数据统计代码!MySQL 8 窗口函数真香
java·sql·mysql