본문 바로가기
Blog/Sparta

99클럽 코테 스터디 3일차 TIL + 람다식

by 코젼 2024. 3. 27.
728x90
반응형

백준

좌표 정렬하기 2

https://www.acmicpc.net/problem/11651

 

11651번: 좌표 정렬하기 2

첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다.

www.acmicpc.net

 


  • 오늘의 학습 키워드 : 람다식
  • 공부한 내용 본인의 언어로 정리하기
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Arrays;
    
    public class Main {
      public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());
        int[][] point = new int[N][2];
        for (int i = 0; i < N; i++) {
          String[] input = br.readLine().split(" ");
          point[i][0] = Integer.parseInt(input[0]);
          point[i][1] = Integer.parseInt(input[1]);
        }
    
        Arrays.sort(point, (a, b) -> a[1] != b[1] ? a[1] - b[1] : a[0] - b[0]);
        for (int i=0; i<N; i++) System.out.println(point[i][0] + " " + point[i][1]);
      }
    }
  • 오늘의 회고
    처음에 Comparator 객체를 사용해서 문제를 풀었는데 메모리 초과가 나서 다른 방안을 생각해보았다.
    람다식을 사용하니 깔끔하게 문제를 풀이할 수 있었다!
    람다식 유용하게 쓰일 것 같으니 손에 익혀놓자 ㅎ_ㅎ

 

Comparator 객체로 푼 풀이 (메모리 초과)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;

public class Main {

  public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int N = Integer.parseInt(br.readLine());
    int[][] point = new int[N][N];

    for (int i=0; i<N; i++) {
      String[] input = br.readLine().split(" ");
      point[i][0] = Integer.parseInt(input[0]);
      point[i][1] = Integer.parseInt(input[1]);
    }

    Arrays.sort(point, new Comparator<int[]>() {
      @Override
      public int compare(int[] o1, int[] o2) {
        if (o1[1] == o2[1])
          return o1[0] - o2[0];
        return o1[1] - o2[1];
      }
    });

    for (int i=0; i<N; i++) {
      System.out.println(point[i][0] + " " + point[i][1]);
    }
  }
}
 

99클럽 1기를 수강하면서 작성한 글입니다.

https://99club.oopy.io/

 

99클럽-1기 모집 중

현직 개발자와 함께하는 코테 스터디

99club.oopy.io

 

728x90
반응형

댓글