백준 | 11650 : 좌표 정렬하기 (Java)

usuyn·2021년 9월 9일
0

알고리즘

목록 보기
1/12

문제에 대한 자세한 정보는 백준 | 11650번 : 좌표 정렬하기에서 확인할 수 있다.


풀이

  1. x, y를 객체 변수로 가지는 Coordinate class를 작성한다.
  2. Coordinate 객체를 요소로 가지는 ArrayList를 생성한다.
  3. Collections.sort() 사용을 위해 Coordinate class에 compareTo 메소드를 구현한다.
  4. x, y를 입력받아 Coordinate 객체를 생성해 ArrayList에 저장한다.
  5. Collections.sort()를 사용해 ArrayList 요소들을 정렬하고 출력한다.

소스코드

import java.io.*;
import java.util.*;

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

	public Coordinate(int x, int y) {
		this.x = x;
		this.y = y;
	}

	@Override
	public int compareTo(Coordinate o) {
		if (this.x == o.x) {
			return this.y - o.y;
		}
		return this.x - o.x;
	}

	@Override
	public String toString() {
		return this.x + " " + this.y + "\n";
	}

}

public class Main {

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

		ArrayList<Coordinate> list = new ArrayList<>();

		int n = Integer.parseInt(br.readLine());

		for (int i = 0; i < n; i++) {
			StringTokenizer temp = new StringTokenizer(br.readLine());
			int x = Integer.parseInt(temp.nextToken());
			int y = Integer.parseInt(temp.nextToken());
			list.add(new Coordinate(x, y));
		}

		Collections.sort(list);

		for (int i = 0; i < n; i++) {
			bw.write(list.get(i).toString());
		}

		br.close();
		bw.close();
	}

}

메모리, 시간

메모리 : 53532KB
시간 : 808ms


풀이 후

문제를 보자마자 당연하게 class를 구현할 생각부터 했다. 풀고 나서 다른 풀이들을 찾아봤는데 2차원 배열에 저장 후
Arrays.sort(arr, new Comparator<int[]>() {});를 사용할 수 있다는 걸 깨달았다. 왜 자꾸 복잡한 쪽으로 생각이 가는지 모르겠다...

profile
https://select-dev-from.tistory.com 로 이사 중

0개의 댓글