P为给定的二维平面整数点集。定义 P 中某点x,如果x满足 P 中任意点都不在 x 的右上方区域内(横纵座标都大于x),则称其为“最大的”。求出所有“最大的”点的集合。(所有点的横座标和纵座标都不重复, 座标轴范围在[0, 1e9) 内)
如下图:实心点为满足条件的点的集合。请实现代码找到集合 P 中的所有 ”最大“ 点的集合并输出。
输入描述:
第一行输入点集的个数 N, 接下来 N 行,每行两个数字代表点的 X 轴和 Y 轴。
对于 50%的数据, 1 <= N <= 10000;
对于 100%的数据, 1 <= N <= 500000;
输出描述:
输出“最大的” 点集合, 按照 X 轴从小到大的方式输出,每行两个数字分别代表点的 X 轴和 Y轴。
输入例子1:
5
1 2
5 3
4 6
7 5
9 0
输出例子1:
4 6
7 5
9 0
import java.util.*;
public class MaxXY {
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
int count = sc.nextInt();
SortedSet<Integer> xSet = new TreeSet<>();
SortedSet<Integer> _ySet = new TreeSet<>();
HashMap<Integer, Integer> xyHs = new HashMap<>();
HashMap<Integer, Integer> yxHs = new HashMap<>();
for (int i=0; i < count; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
xSet.add(x);
_ySet.add(y*(-1));
xyHs.put(x, y);
yxHs.put(y, x);
}
Iterator<Integer> vx = xSet.iterator();
while(vx.hasNext()){
int x = vx.next();
int y = xyHs.get(x);
boolean flag = true;
Iterator<Integer> vy = _ySet.iterator();
while(vy.hasNext()){
int tmp_y = vy.next() * (-1);
if (tmp_y > y){
int tmp_x = yxHs.get(tmp_y);
if (x < tmp_x){
flag = false;
break;
}
}
}
if (flag)
System.out.println(x + " " + y);
}
sc.close();
}
}
今天不想写太复杂的算法,直接用jdk提供的hashMap和hashSet求解
由于时间复杂度问题,牛客网过百分之50的用例,待有空再优化,先在此记录一下