문제 |
Binary Search - LeetCode
Can you solve this real interview question? Binary Search - Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
leetcode.com
코드 |
class Solution
{
public:
int search(vector<int> &nums, int target)
{
int lo = 0;
int hi = nums.size() - 1;
while (lo <= hi)
{
int md = (lo + hi) / 2;
if (nums[md] == target)
{
return md;
}
(nums[md] < target) ? lo = md + 1: hi = md - 1;
}
return -1;
}
};
설명 |
오름차순으로 정렬된 벡터 nums와 검색할 정수 target을 입력받았을 때,
target에 해당하는 인덱스를 출력하는 문제이다.
target이 nums에 존재하지 않으면 -1을 출력한다.
벡터의 첫번째 수를 lo, 마지막 수를 hi로 설정하고 중간 지점을 탐색한다.
중간 지점에 해당하는 수가 target이면 바로 return하고, 그렇지 않다면 불가능한 구간을 배제한다.
'PS > LeetCode' 카테고리의 다른 글
[C++] LeetCode (릿코드) 977 : Squares of a Sorted Array (0) | 2023.03.24 |
---|---|
[C++] LeetCode (릿코드) 35 : Search Insert Position (0) | 2023.03.24 |
[C++] LeetCode (릿코드) 278 : First Bad Version (0) | 2023.03.24 |