[BaekJoon] #2920 - 음계 [Java][C++]
[BaekJoon] #2920 - 음계 [Java][C++]
1. 아이디어
오름차순인지 내림차순인지를 판단하는 불 타입 변수들을 활용했다. 현재 음이 이전 음보다 큰지 작은지로 해당 변수를 갱신해서 최종적으로 ascending인지, descending인지, 아니면 mixed인지 판별했다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(1)$ | $O(1)$ |
3. 코드
풀이 [Java][C++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int[] arr = new int[8];
for (int i = 0; i < 8; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
boolean isAsc = true;
boolean isDesc = true;
for (int i = 1; i < 8; i++) {
if (arr[i] < arr[i - 1]) isAsc = false;
if (arr[i] > arr[i - 1]) isDesc = false;
}
if (isAsc) {
System.out.println("ascending");
} else if (isDesc) {
System.out.println("descending");
} else {
System.out.println("mixed");
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
vector<int> v(8);
for (int& x : v) cin >> x;
bool is_asc = true;
bool is_desc = true;
for (int i = 1; i < 8; i++) {
if (v[i] < v[i - 1]) is_asc = false;
if (v[i] > v[i - 1]) is_desc = false;
}
if (is_asc) {
cout << "ascending";
} else if (is_desc) {
cout << "descending";
} else {
cout << "mixed";
}
}
This post is licensed under CC BY 4.0 by the author.