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

这个题我一开始想着用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());
		}
	}
}
相关推荐
白鸽(二般)2 小时前
MinIO Java Client API
java·开发语言
普通攻击往后拉2 小时前
Leetcode 206. 反转链表
算法·leetcode·链表
软萌萌的13 小时前
Java Spring Boot 修改yml配置&加载顺序规则
java·spring boot·python
@syh.3 小时前
【贪心】矩阵消除游戏
算法·游戏·矩阵
IT小盘3 小时前
13-企业Prompt模板-角色任务约束与输出格式
java·前端·prompt
爱敲键盘的猴子3 小时前
Java并发编程 -- volatile
java·java并发
可编程芯片开发4 小时前
基于零极点配置的PID控制系统simulink建模与仿真
算法
徐小夕4 小时前
开源!我用SQLite + DuckDB打造了一款可视化AI问数平台
前端·算法·github
Hrain-AI4 小时前
2026 企业 AI 智能体平台横评:8 大主流平台 7 维度实测对比
人工智能·算法·机器学习