import java.util.Arrays;
import java.util.Scanner;
public class problem245 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int size = in.nextInt();
int match = in.nextInt();
int count = 0; // 갯수 초기화
int[] arr = new int[size];
// 양 쪽 끝에 포인터 지정
int start = 0;
int end = size - 1;
for (int i = 0; i < size; i++) {
arr[i] = in.nextInt();
}
Arrays.sort(arr);
// 1 2 3 4 5 7
while (start < end) {
if (arr[start] + arr[end] < match) {
start++;
} else if (arr[start] + arr[end] == match) {
// 값이 같을 경우 포인터를 두개다 이동(한번 쓴 값은 사용 X)
count++;
start++;
end--;
} else {
end--;
}
}
System.out.print(count);
}
}
import java.util.Scanner;
import java.util.Stack;
public class problem246 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
Stack<Integer> stack = new Stack<>();
int size = in.nextInt();
int start = 0;
for (int i = 0; i < size; i++) {
int value = in.nextInt();
if (value > start) {
for (int j = start + 1; j <= value; j++) {
stack.push(j); // 스택에 start + 1 부터 값 저장
sb.append("+").append("\n");
}
start = value; // start를 value값으로 초기화
} else if (stack.peek() != value) {
System.out.println("NO");
return;
}
stack.pop();
sb.append("-").append("\n");
}
System.out.println(sb.toString());
}
}
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class problem247 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
Queue<Integer> q = new LinkedList<>();
for (int i = 1; i <= n; i++) {
q.add(i);
}
while (q.size() > 1) {
q.poll(); // 맨 위의 값을 버린다 (꺼낸다)
int temp = q.poll(); // 다음 맨위의 값을 꺼낸다.
q.add(temp); // 그 값을 q에 담아준다. (Queue의 특징에 따라 FIFO)
}
System.out.print(q.poll());
}
}
백준 11286번 (우선순위 큐)
정렬기준을 재정의 하는점이 어려웠다.
import java.util.PriorityQueue;
import java.util.Scanner;
public class problem248 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
PriorityQueue<Integer> pq = new PriorityQueue<>((o1, o2) -> {
// 정렬 기준을 재정의 한다
int first = Math.abs(o1);
int second = Math.abs(o2);
// 절대값이 같은 경우 음수 우선
if (first == second) {
if (o1 > o2) {
return 1;
}
return -1;
}
// 절대값 작은 데이터 우선
return first - second;
});
for (int i = 0; i < n; i++) {
int val = in.nextInt();
// 입력값이 0이거나 우선순위 큐가 비어있을경우.
if (val == 0) {
if (pq.isEmpty()) System.out.println("0");
else System.out.println(pq.poll());
} else {
pq.add(val);
}
}
}
}