[BaekJoon] 11931번 - 수 정렬하기 4 [Java][C++]
[BaekJoon] 11931번 - 수 정렬하기 4 [Java][C++]
1. 아이디어
주어진 수들을 내림차순으로 바로 정렬해도 되고, 오름차순으로 정렬 후 역방향 탐색을 통해 내림차순으로 정렬한 것처럼 출력해줘도 된다.
2. 코드
1. 풀이 [Java]
Java에서 sort 메서드는 기본 타입 배열일 경우 내림차순으로 정렬할 수 없어서 오름차순 정렬 후 역방향 탐색으로 내림차순 출력해줬다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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));
StringBuilder sb = new StringBuilder();
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(br.readLine());
}
Arrays.sort(arr);
for (int i = n - 1; i >= 0; i--) {
sb.append(arr[i]).append("\n");
}
System.out.println(sb);
}
}
2. 풀이 [C++]
C++의 역방향 반복자를 활용해 내림차순 정렬을 바로 해줬다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
vector<int> v(n);
for (int& x : v) cin >> x;
sort(v.rbegin(), v.rend());
for (int x : v) {
cout << x << '\n';
}
}
3. 디버깅
없음.
4. 참고
없음.
This post is licensed under CC BY 4.0 by the author.