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

这个题我一开始想着用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());
		}
	}
}
相关推荐
郑州光合科技余经理23 分钟前
代驾系统架构拆解:订单链路、权限组织与私有化源码交付
开发语言·后端·算法·架构·系统架构·uni-app·php
To_OC3 小时前
LC 35 搜索插入位置:二分查找谁都会,边界条件谁写谁懵
javascript·算法·leetcode
天才测试猿3 小时前
2026软件测试面试八股文(含答案+文档)
自动化测试·软件测试·python·功能测试·测试工具·面试·职场和发展
码哥DFS3 小时前
二叉树的直径
开发语言·javascript·算法
Pluchon4 小时前
Java个人综合项目——萌部落社区V2.0
java·python·spring·spring cloud·postman·idea
梦雨生生5 小时前
java开发工具(学习第一天)
java·开发语言·学习
她说可以呀6 小时前
Spring-ai-alibaba文生图
java·人工智能·spring
营养充电站6 小时前
KMP全栈开发:从Android到AI Agent的技术演进与实践
人工智能·算法·docker·jupyter
技术小黑7 小时前
RNN算法实战系列05 | 天气预测
人工智能·rnn·算法