12/20 자바 코테
1931
회의 시작시간과 종료시간들을 통해 이 회의실에서 최대로 진행할 수 있는 회의의 수를 구하는 문제이다.
-
핵심 아이디어
이 문제의 핵심은 회의 시작과 종료 시간이 주어졌을 때, 먼저 종료시간을 기준으로 정렬하고, 종료시간이 같다면, 시작시간을 기준으로 정렬한다.
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[][] time = new int[n][2];
for (int i = 0; i < n; i++) {
time[i][0] = scanner.nextInt();
time[i][1] = scanner.nextInt();
}
// 회의 종료시간을 기준으로 정렬
// 회의 종료시간이 같다면, 시작 시간을 기준으로 정렬
Arrays.sort(time, (a, b) -> {
if (a[1] == b[1]) {
return Integer.compare(a[0], b[0]);
} else {
return Integer.compare(a[1], b[1]);
}
});
int result = 0;
int prevTime = 0;
// 이전의 회의 종료 시간보다 현재 회의 시작 시간이 크거나 같다면 count
for (int i = 0; i < n; i++) {
if (time[i][0] >= prevTime) {
result++;
prevTime = time[i][1];
}
}
System.out.println(result);
}
}
1541
+와 -로 이어진 식에 임의로 괄호를 쳐서 연산 순서를 바꾼다고 할 때, 최솟값을 만드는 문제이다.
괄호로 연산의 순서를 바꾸는 역할을 하기 위해서는 split()메서드를 이용해 +로 이어진 문자열을 따로 뽑아내면 된다.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String expression = scanner.next();
String[] substract = expression.split("-");
int result = 0;
for (int i = 0; i < substract.length; i++) {
String[] add = substract[i].split("\\+");
int temp = 0;
for (int j = 0; j < add.length; j++) {
temp += Integer.parseInt(add[j]);
}
if (i == 0) {
result += temp;
} else {
result -= temp;
}
}
System.out.println(result);
}
}
1026
-
int(primitive type) : 기본 자료형으로, 정수를 표현한다.
산술 연산 가능
메서드, 객체 지향적 기능을 제공하지 않는다
메모리 효율이 높고 성능이 좋다
null값 초기화 불가능
-
Integer(wrapper class) : 기본 타입을 객체로 다루기 위해 사용하는 클래스
객체로 동작
메서드를 제공
primitive type으로 변환하지 않으면 산술 연산 불가능
null값 처리 가능
ArrayList, HashMap과 같은 컬렉션 프레임워크에서 사용할 수 있다.
-
Primitive type
성능이 중요한 경우(많은 연산을 해야 하는 경우)
간단히 값을 저장하고 연산을 할 때
-
Wrapper class
컬렉션과 함께 사용할 때
null을 다뤄야 할 때
객체의 메서드를 사용해야 할 때
import java.util.Scanner;
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
// Comparator로 역순으로 정렬할 때는 Integer 타입으로 선언해야함
Integer[] a = new Integer[n];
Integer[] b = new Integer[n];
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
}
for (int i = 0; i < n; i++) {
b[i] = scanner.nextInt();
}
Arrays.sort(a);
// 내림차순 정렬
// Comparator 라이브러리 암기
Arrays.sort(b, Comparator.reverseOrder());
int result = 0;
for (int i = 0; i < n; i++) {
result += a[i] * b[i];
}
System.out.println(result);
}
}
1789
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long n = scanner.nextLong();
long sum = 0;
int result = 0;
for (int i = 1; ; i++) {
if (sum > n) {
result--;
break;
} else {
sum += i;
result++;
}
}
System.out.println(result);
}
}
댓글남기기