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

这个题我一开始想着用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());
		}
	}
}
相关推荐
geovindu9 小时前
go: Enumeration Algorithm
开发语言·后端·算法·golang·枚举算法
退休倒计时9 小时前
【每日一题】LeetCode 287. 寻找重复数 TypeScript
算法·leetcode·typescript
C++、Java和Python的菜鸟9 小时前
第2章 前端Web基础(js、vue+Ajax)
java
harmful_sheep9 小时前
idea相关设置
java·ide·intellij-idea
奋发向前wcx9 小时前
y1,y2总复习笔记2 2026.7.15
java·笔记·算法
天才测试猿9 小时前
如何封装自动化测试框架?
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
AI科技星9 小时前
《全域数学·工程应用大典》113–200讲完整总目录
数据结构·人工智能·算法·机器学习·线性回归·乖乖数学·全域数学
ttod_qzstudio9 小时前
【软考算法】软件设计师下午第四题算法总纲:从“直接放弃“到“稳稳拿分“
算法·软考
han_hanker10 小时前
mybatis-plus 常用方法
java·tomcat·mybatis
广州灵眸科技有限公司10 小时前
xfce桌面旋转说明:基于灵眸科技EASY-EAI-Nano-TB
网络·网络协议·tcp/ip·算法·php