문제
https://www.acmicpc.net/problem/1920
1920번: 수 찾기
첫째 줄에 자연수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 줄에는 N개의 정수 A[1], A[2], …, A[N]이 주어진다. 다음 줄에는 M(1 ≤ M ≤ 100,000)이 주어진다. 다음 줄에는 M개의 수들이 주어지는데, 이 수들
www.acmicpc.net
풀이
이진 탐색을 적용하면 데이터 정렬까지 고려하여 O(nlogn) 시간 복잡도로 해결할 수 있다.
이진 탐색(Binary Search) 알고리즘
이진 탐색(Binary Search) 알고리즘 탐색 범위를 반으로 줄여나가면서 데이터를 빠르게 탐색하는 알고리즘 이진 탐색 핵심 이론 특징 - 배열 내부의 데이터가 정렬되어 있어야만 사용할 수 있다. -
soobin0821.tistory.com
코드
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
static int N;
static vector<int> A;
bool binary_search(int num);
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> N;
A.resize(N);
for(int i = 0; i < N; i++)
{
cin >> A[i]; // 배열 A 저장
}
sort(A.begin(), A.end()); // 배열 A 정렬 시간 복잡도: O(nlogn)
int M;
cin >> M;
for(int i = 0; i < M; i++)
{
int num;
cin >> num;
if(binary_search(num))
{
cout << "1\n";
}
else
{
cout << "0\n";
}
}
return 0;
}
bool binary_search(int num)
{
int starti = 0;
int endi = N - 1;
while(starti <= endi)
{
int midi = (starti + endi) / 2;
if(num == A[midi])
{
return true;
}
else if(num < A[midi])
{
endi = midi - 1;
}
else if(num > A[midi])
{
starti = midi + 1 ;
}
}
return false;
}
더보기
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int N, M;
cin >> N;
vector<int> A(N);
for(int i = 0; i < N; i++)
{
cin >> A[i];
}
// 배열 A 정렬 시간 복잡도 : O(nlogn)
sort(A.begin(), A.end());
cin >> M;
for(int i = 0; i < M; i++)
{
bool find = false;
int target;
cin >> target;
// 이진 탐색 시작
int start = 0;
int end = A.size() - 1;
while(start <= end)
{
int midi = (start + end) / 2;
int midV = A[midi];
if(midV > target)
{
end = midi - 1;
}
else if(midV < target)
{
start = midi + 1;
}
else
{
find = true;
break;
}
}
if(find)
{
cout << 1 << "\n";
}
else
{
cout << 0 << "\n";
}
}
}
728x90
'코딩테스트 > 백준' 카테고리의 다른 글
[백준][C++]1456번 거의 소수 (0) | 2023.07.04 |
---|---|
[백준][C++]2193번 이친수 (0) | 2023.07.04 |
[백준][C++]2178번 미로 탐색 (0) | 2023.07.03 |
[백준][C++]1016번 제곱 ㄴㄴ 수 (0) | 2023.07.02 |
[백준][C++]2018번 수들의 합 5 (0) | 2023.06.15 |