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的用例,待有空再優化,先在此記錄一下