본문 바로가기

Algorithm_BOJ(백준)/정렬

[백준 11004 c++ O] K번째 수

728x90
반응형

1.참고 풀이

; 더 빠른 정렬 시간

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
31
32
33
34
35
36
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring> // memset 헤더
#include <string>
using namespace std;
// [백준 11004 c++ O] K번째 수  
// 문제: n개의 수 중 오름차순으로 k번째 수를 출력
// 접근: 단순 sort 후 k 번째 수 출력 -> 통과 하지만 시간 2배
// 접근2: nth_element 로 정렬
// 시간복잡도: O(n) , 입력n, 정렬nlog(n) , 
// 풀이: 
// 벡터에 수 입력
// 정렬 후 k번재 출력
// 개념:
// nth_element(v.begin(), v.begin()+ 0, v.end()); : 원하는 인덱스 까지만 정렬
int n, k;
vector<int> a;
int main()
{
    ios::sync_with_stdio(false); // 계산시간 단축 // cin,scanf 같이 쓰면 오류
    cin.tie(nullptr); cout.tie(nullptr);// 입출력 시간 단축 // 이것을 쓰면 scanf,printf섞어 쓰면 안됨
 
    cin >> n >> k;
    for (int i = 1; i <= n; i++) {
        int num; 
        cin >> num;
        a.push_back(num);
    }
 
    nth_element(a.begin(), a.begin()+ k-1, a.end()); // k번째 까지만 정렬
    cout << a[k - 1<< '\n';
    return 0;
}
 
cs

 

2.  내 풀이 일반 정렬

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
31
32
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring> // memset 헤더
#include <string>
using namespace std;
// [백준 11652 c++ V] 카드  
// 문제: 
// 접근: 해쉬로 해당 수의 갯수 벡터에 저장 해놓고 제일 큰 값 인덱스 출력 -> 메모리 초과
// 접근2: 벡터에 입력 후 정렬하고 나오는 수 완탐 
// 시간복잡도: O(n)
// 풀이: 
int n, k;
vector<int> a;
int main()
{
    ios::sync_with_stdio(false); // 계산시간 단축 // cin,scanf 같이 쓰면 오류
    cin.tie(nullptr); cout.tie(nullptr);// 입출력 시간 단축 // 이것을 쓰면 scanf,printf섞어 쓰면 안됨
 
    cin >> n >> k;
    for (int i = 1; i <= n; i++) {
        int num; 
        cin >> num;
        a.push_back(num);
    }
 
    sort(a.begin(), a.end());
    cout << a[k - 1<< '\n';
    return 0;
}
 
cs
반응형

'Algorithm_BOJ(백준) > 정렬' 카테고리의 다른 글

[백준 2711 c++ O] 세수정렬  (0) 2021.08.30
[백준 5635 c++ OO] 생일  (0) 2021.08.20
[백준 11652 c++ V] 카드  (0) 2021.08.06
[백준 10825 c++ O] 국영수  (0) 2021.08.06
[백준 10814 c++ VV] 나이순 정렬  (0) 2021.08.06