Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 운영체제와 정보기술의 원리
- B tree 데이터삽입
- 개발남노씨
- 온디바이스AI
- CPU 스케줄링
- 코딩애플
- concurrency control
- BreadcrumbsComputer-Networking_A-Top-Down-Approach
- SDK
- Git
- 쉬운코드
- 백엔드
- 김영한
- SQL
- 반효경
- 운영체제
- vite
- 갤럭시 S24
- 트랜잭션
- 커널 동기화
- 네트워크
- 시그널 핸들러
- 인터럽트
- 데이터베이스
- recoverability
- 프로세스 주소 공간
- Extendable hashing
- 쉬운 코드
- 코딩테스트 [ ALL IN ONE ]
- 시스템프로그래밍
Archives
- Today
- Total
티끌모아 태산
1920: 수 찾기 본문
728x90
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
설명
N개의 정수 A[1], A[2], …, A[N]이 주어져 있을 때, 이 안에 X 라는 정수가 존재하는지 알아내는 프로그램을 작성하시오.
핵심 아이디어
- N개의 정수에서 X가 있는지 탐색하는 문제이다. N의 최대가 100,000이기 때문에 2중 for문을 사용하면 시간초과 발생한다. 따라서 규모가 큰 데이터에서 target 값을 찾기 수월한 이진 탐색 을 사용하자. 이진 탐색의 시간 복잡도는 O(logN)을 보장하며, 반드시 정렬된 상태에서 사용해야 한다.
코드 구현
C++
해당 코드는 이진 탐색을 직접 구현해서 풀이 한것이다.
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
using namespace std;
int n;
vector<int> arr;
int m;
vector<int> ans;
int binarySearch(vector<int>& arr, int start, int end, int target) {
int mid;
while (start <= end) {
mid = (start + end) / 2;
if (arr[mid] == target) {
return 1;
}
else if (arr[mid] > target) end = mid - 1;
else if (arr[mid] < target) start = mid + 1;
}
return 0;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for (int i = 0; i < n; i++) {
int num;
cin >> num;
arr.push_back(num);
}
sort(arr.begin(), arr.end());
cin >> m;
while (m--) {
int target;
cin >> target;
int result;
result = binarySearch(arr, 0, n - 1, target);
ans.push_back(result);
}
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << "\n";
}
}
해당 코드는 이진 탐색 기능을 가져와서 사용한 것!
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
using namespace std;
int n; // 자연수 n
vector<int> arr; // 자연수 입력 받기
int m; // target 개수
vector<int> ans; // 결과를 저장할 벡터
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for (int i = 0; i < n; i++) {
int num;
cin >> num;
arr.push_back(num);
}
// 이진 탐색을 위해 정렬한다.
sort(arr.begin(), arr.end());
cin >> m;
while (m--) {
int target;
cin >> target;
if (binary_search(arr.begin(), arr.end(), target)) {
ans.push_back(1);
}
else {
ans.push_back(0);
}
}
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << "\n";
}
return 0;
}
728x90
'백준 문제 > 이진 탐색' 카테고리의 다른 글
10815: 숫자 카드 (0) | 2024.04.04 |
---|