본문 바로가기

전체 글

(98)
5052번:전화번호 목록(Java) 문제에서 전화번호는 10자리 이하라고 했다. int 자료형의 범위는 -2,147,483,648 ~ 2,147,483,647 이므로 int 자료형을 쓰면 모든 전화번호를 저장할 수 없으므로 String 배열을 전화번호부로 사용했다. 전화번호를 입력받고 Arrays.sort()로 오름차순으로 정렬한 후, startsWith 함수로 현재 index + 1 번째 문자열이 현재 index를 포함하는지 검사한 후 출력했다. 오름차순으로 정렬되어 있으므로 +1 번째만 검사하면 된다. 이렇게 하면 시간복잡도를 O(n^2)으로 줄일 수 있다. 결과 코드 import java.util.*; public class Main { public static void main(String[] args) { Scanner scann..
5430번:AC(Java) int 배열과 시작, 끝, 현재 index를 사용해 풀었다. R을 할 때마다 순서를 바꾸는 것은 시간이 너무 오래 걸릴 것이라 판단했다. 배열을 그대로 두고 연산 실행 시 시작, 끝, 현재 index 연산만 하면 시간복잡도를 줄일 수 있을 거라고 생각했다. 메모리는 D를 할 때마다 조금씩 낭비될 수는 있지만 시간을 줄이는 것이 더 이득이라 생각한 결과이다. 변수들을 다음과 같이 선언했다. BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int[] list;//배열 int n = Integer.parseInt(br.readLine());//반복 횟수 String[] order;//명령 int size;//배열 크기 int ..
1927번:최소 힙(Java) PriorityQueue를 사용했다. 오름차순으로 우선순위가 되는 PriorityQueue를 선언하고 0이 입력되면 PriorityQueue가 비어있는지 확인 후 출력한다. 0이 아닌 수가 입력되면 PriorityQueue에 add 해 준다. 결과 코드 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(Sy..
11286번:절댓값 힙(Java) PriorityQueue를 두 개 사용해 풀었다. 양수를 저장하는 positive PriorityQueue는 오름차순으로 정령하도록 선언하고 음수를 저장하는 negavite PriorityQueue는 내림차순으로 정렬하기 위해 Collections.reverseOrder()를 사용했다. 입력된 수의 조건에 따라 저장했다. 0이 입력됐을 때는 PriorityQueue의 peek()를 통해 절댓값을 비교해 출력했다. 변수 선언 Scanner scanner = new Scanner(System.in); PriorityQueue positive = new PriorityQueue(); PriorityQueue negative = new PriorityQueue(Collections.reverseOrder());..
1302번: 베스트셀러(Java) HashMap을 써서 제목과 입력 횟수를 저장하고 keySet을 순환하면서 최대로 입력받는 제목을 구함과 동시에 사전순으로 제일 빠른 제목을 찾았다. 우선 HashMap을 써서 제목을 입력받을 때마다 몇 번 입력받았는지 Value에 저장했다. Scanner scanner = new Scanner(System.in); String title; HashMap list = new HashMap(); int n = scanner.nextInt(); int max = 1; String result; for(int i = 0; i max) { result = i; max = list.get(i); } else if(list.get(i) == max && i.compareTo(result) < 0) { result ..