Search Insert Position

ㅋㅋ·2023년 2월 20일
0

알고리즘-leetcode

목록 보기
115/135

오름차순으로 정렬된 정수형 벡터에서 target 정수가 존재한다면 인덱스를 반환하고,

없다면 오름차순을 유지하며 target을 추가할 수 있는 인덱스를 반환하는 문제

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        
        int head{0};
        int tail = nums.size() - 1;

        int body{0};
        while (head <= tail)
        {
            body = ((tail - head) >> 1) + head;
            if (nums[body] == target)
            {
                return body;
            }
            else if (nums[body] < target)
            {
                head = body + 1;
            }
            else
            {
                tail = body - 1;
            }
        }

        return head;
    }
};

0개의 댓글