The biggest problem in today's headlines

Problem Description:


enter:

5

1 2

5 3

4 6

7 5

9 0

Output:

4 6

7 5

9 0

Idea: First sort in descending order of y, and then loop through the x coordinates. When x is the maximum x value of the current traverse coordinates, it is the desired coordinate. Use x as the key to add to the TreeMap. Finally, traverse the TreeMap to output the coordinates and time. The complexity is nlgn+n.

//平面点集的“最大”点集(即该点的右上角没有点,横纵坐标都不大于该点) 时间复杂度nlogn
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class MaxPoint {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int x, y = 0;
		// 将点按照y降序,x升序排列.以y为键,降序排列
		TreeMap<Integer, Integer> out = new TreeMap<>();
		TreeMap<Integer, Integer> pt = new TreeMap<>(new Comparator<Integer>() {

			@Override
			public int compare(Integer o1, Integer o2) {

				return o2 - o1;
			}

		});

		for (int i = 0; i < n; i++) {
			x = sc.nextInt();
			y = sc.nextInt();
			pt.put(y, x);
		}

		// 将x大于前面所有值的最大值所在的坐标加入map
		Iterator<Map.Entry<Integer, Integer>> it = pt.entrySet().iterator();
		int max = -1;
		while (it.hasNext()) {
			Map.Entry<Integer, Integer> entry = it.next();
			if (entry.getValue() > max) {
				max = entry.getValue();
				out.put(entry.getValue(), entry.getKey());
			}
		}

		// 遍历输出
		Iterator<Map.Entry<Integer, Integer>> itOut = out.entrySet().iterator();
		while (itOut.hasNext()) {
			Map.Entry<Integer, Integer> entry = itOut.next();
			System.out.println(entry.getKey() + " " + entry.getValue());
		}
	}
}


Guess you like

Origin blog.csdn.net/m0_37541228/article/details/77503998