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

这个题我一开始想着用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());
		}
	}
}
相关推荐
Tisfy3 小时前
LeetCode 1288.删除被覆盖区间:排序(非二重循环暴力)
算法·leetcode·题解·排序
一路向北North3 小时前
Spring Security OAuth2.0(18):资源服务测试
java·后端·spring
阿文的代码库3 小时前
经典算法题剖析:按奇偶排序数组
数据结构·算法
AI小码3 小时前
WAIC 2026前瞻:AI产业进入拼落地的下半场
人工智能·算法·ai·程序员·大模型·编程·智能体
极光代码工作室4 小时前
基于SpringBoot的订单管理系统
java·springboot·web开发·后端开发
xiaoduzi19914 小时前
ConcurrentHashMap学习
java·学习
折哥的程序人生 · 物流技术专研4 小时前
《Java 100 天进阶之路》第53篇:volatile与JMM(2026版)
java·volatile·内存屏障·可见性·java内存模型·jmm·java100天进阶
米饭不加菜4 小时前
使用万用表判断三极管(BJT)好坏
java·开发语言
珠海西格电力4 小时前
零碳园区数据应用的具体场景有哪些?
大数据·人工智能·算法·架构·能源
geovindu4 小时前
CSharp: Dijkstra Algorithms
开发语言·后端·算法·c#