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
- serverless
- 분산시스템
- kubernetes
- IaC
- PACELC
- Validation
- fcm
- sns
- terraform
- SageMaker
- CHECK
- amazonqcli
- rds
- cloudwatch
- aws
- lambda
- 병목
- Lamda
- CAP
Archives
- Today
- Total
잡다한 IT 지식
[LeetCode] - 35. Search Insert Position 본문
문제 출처 : https://leetcode.com/problems/search-insert-position/description/
[문제 설명]
The array is sorted. so you can use a binary search algorithm, not a linear search.
the time complexity of a linear search is O(N) but a binary search is O(logN). (N is the size of the array)
The given array has consisted of distinct integers. So if you find a target's index then you should return the index.
if you can't find an index of the target then index of the left is the answer.
class Solution {
public:
// 길이는 1이상
int searchInsert(vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target){
right = mid - 1;
} else {
return mid;
}
}
return left;
}
};
'알고리즘 문제 풀이 > 이분탐색' 카테고리의 다른 글
5207. 파이썬 SW 문제해결 구현 4일차 - 이진 탐색 (0) | 2025.04.29 |
---|---|
백준 - N번째 큰 수 (0) | 2022.06.24 |
백준 - 공유기 설치(Kotlin) (0) | 2022.02.15 |
백준 - 랜선 자르기(Java) (0) | 2022.01.17 |
백준 - 숫자 카드 (0) | 2022.01.04 |