【今日頭條2017內推筆試題】二維平面整數點集

這裏寫圖片描述

解題思路
對所有的座標點對y進行排序,然後按y排序順序由大到小進行遍歷,定義一個變量來保存當前已經遍歷座標點的最大x值,如果,後序節點的x值大於保存的最大x值,則輸出。

因爲已經對y按大小進行排序,越往後遍歷y值越小,而這個點想爲邊界點只能x值大於已經遍歷序列的最大x值。這個x是逐漸遞增的,題意要求x從小到大輸出,因而直接輸出即可。


import java.util.Arrays;
import java.util.Scanner;

class Node implements Comparable<Node> {
    int x;
    int y;

    @Override
    public int compareTo(Node o) {
        // TODO Auto-generated method stub
        return this.y > o.y ? -1 : ((this.y == o.y) ? 0 : 1);
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        Node[] data = new Node[n];

        for (int i = 0; i < n; i++) {
            Node node = new Node();
            node.x = sc.nextInt();
            node.y = sc.nextInt();
            data[i] = node;
        }
        Arrays.sort(data);

        long maxX = Integer.MIN_VALUE;
        for (int i = 0; i < n; i++) {
            if (data[i].x > maxX) {
                maxX = data[i].x;
                System.out.println(data[i].x + " " + data[i].y);
            }
        }

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章