<JAVA> 백준 18870번 : 좌표 압축

eunsiver·2022년 10월 3일
0

<JAVA>백준 알고리즘

목록 보기
8/11
post-thumbnail

업로드중..

시간 초과가 엄청 났던 문제
BufferedReader와 StringBuilder를 꼭 써야할 것 같다.

Key-Value 문제는 HashMap을 사용하자!

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;

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[] sorted = new int[n];
		int[] origin = new int[n];
		StringTokenizer st = new StringTokenizer(br.readLine());

		for (int i = 0; i < n; i++) {
			sorted[i] = Integer.parseInt(st.nextToken());
		}
		origin = sorted.clone();

		Arrays.sort(sorted);

		HashMap<Integer, Integer> map = new HashMap<>();
		int idx = 0;
		for (int e : sorted) {
			if (!map.containsKey(e)) {
				map.put(e, idx++);
			}
		}
		StringBuilder sb = new StringBuilder();
		for (int i : origin) {
			sb.append(map.get(i)).append(" ");
		}
		System.out.println(sb);
	}
}

중요 해결 방법: HashMap(키:값)

	HashMap<Integer, Integer> map = new HashMap<>();
	int idx = 0;
	for (int e : sorted) {
  		  //set없이 해결
		if (!map.containsKey(e)) {
			map.put(e, idx++);
		}
	}
profile
Let's study!

0개의 댓글