본문 바로가기

알고리즘/이분탐색

[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;
    }
};
728x90
반응형

'알고리즘 > 이분탐색' 카테고리의 다른 글

백준 - N번째 큰 수  (0) 2022.06.24
백준 - 공유기 설치(Kotlin)  (0) 2022.02.15
백준 - 랜선 자르기(Java)  (0) 2022.01.17
백준 - 숫자 카드  (0) 2022.01.04
백준 - 수 찾기  (0) 2021.12.25