문제 |
Loading Question... - LeetCode
Search Insert Position - LeetCode
Can you solve this real interview question? Search Insert Position - Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must w
leetcode.com
코드 |
class Solution
{
public:
int searchInsert(vector<int> &nums, int target)
{
int lo = 0;
int hi = nums.size() - 1;
int res = nums.size();
while (lo <= hi)
{
int md = (lo + hi) / 2;
if (nums[md] < target)
{
lo = md + 1;
}
else
{
res = md;
hi = md - 1;
}
}
return res;
}
};
설명 |
오름차순으로 정렬된 벡터와 한 숫자가 주어졌을 때, 오름차순 정렬을 유지하면서 그 숫자를 삽입할 최초의 위치를 찾는 문제이다.
중간 지점이 target보다 작으면 삽입할 수 없기 때문에 왼쪽의 범위를 배제한다.
target보다 크거나 같으면 삽입할 수 있기 때문에 오른쪽 범위를 배제하고 그 인덱스를 저장한다.
반복하면 res에 삽입할 수 있는 최초의 위치가 저장된다.
단, 벡터에 있는 모든 수가 target보다 작을 경우 res는 초깃값에서 변동되지 않기 때문에
res의 초깃값을 마지막 위치로 설정해야 한다.
'PS > LeetCode' 카테고리의 다른 글
[C++] LeetCode (릿코드) 977 : Squares of a Sorted Array (0) | 2023.03.24 |
---|---|
[C++] LeetCode (릿코드) 278 : First Bad Version (0) | 2023.03.24 |
[C++] LeetCode (릿코드) 704 : Binary Search (0) | 2023.03.24 |