본문 바로가기

PS/LeetCode

[C++] LeetCode (릿코드) 704 : Binary Search

문제

Binary Search - LeetCode

 

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하고, 그렇지 않다면 불가능한 구간을 배제한다.