标签:
现在有很多长方形,每一个长方形都有一个编号,这个编号可以重复;还知道这个长方形的宽和长,编号、长、宽都是整数;现在要求按照一下方式排序(默认排序规则都是从小到大);import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = Integer.parseInt(sc.nextLine()); // 有n个测试数据 while (n-- > 0) { // 接收有几个矩形 int count = Integer.parseInt(sc.nextLine());// count=8 Set<Rect> set = new HashSet<Rect>(); for (int i = 0; i < count; i++) { String rectStr = sc.nextLine();// 1 2 1 String[] rectS = rectStr.split(" "); // 计算出矩形的长和宽 int length = Math.max(Integer.parseInt(rectS[1]), Integer.parseInt(rectS[2])); int width = Math.min(Integer.parseInt(rectS[1]), Integer.parseInt(rectS[2])); Rect rect = new Rect(Integer.parseInt(rectS[0]), length, width); set.add(rect); } List<Rect> list = new ArrayList<Rect>(set); Collections.sort(list, new MyComparator()); for (Rect rect : list) { System.out.println(rect.id + " " + rect.length + " " + rect.width); } } } } // 定义我自己的比较器 class MyComparator implements Comparator<Rect> { /** * 两个矩形,若果矩形id不同,就按照矩形升序排列 如果矩形id同,就按照矩形的长升序排列 如果矩形id同,并且矩形的长同,就按照矩形的宽升序排序 */ @Override public int compare(Rect o1, Rect o2) { if (o1.id != o2.id) { return o1.id - o2.id; } else if (o1.length != o2.length) { return o1.length - o2.length; } else { // 说明id和length也相同 return o1.width - o2.width; } } } class Rect { int id; int length;// 矩形的长 int width;// 矩形的宽 public Rect(int id, int length, int width) { this.id = id; this.length = length; this.width = width; } // 这里重新equals方法和hashCode,用id和length和width来标识 @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; result = prime * result + length; result = prime * result + width; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Rect other = (Rect) obj; if (id != other.id) return false; if (length != other.length) return false; if (width != other.width) return false; return true; } }
标签:
原文地址:http://blog.csdn.net/x380481791/article/details/51346133