알고리즘 문제 풀이/이분탐색

[LeetCode] - 35. Search Insert Position

가나무마 2023. 7. 5. 21:58

문제 출처 : 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;
    }
};