[Leetcode] 35. Search Insert Position

whitehousechef·2025년 5월 24일

https://leetcode.com/problems/search-insert-position/description/?envType=study-plan-v2&envId=top-interview-150

intial

a typical bs but if target is bigger than what elements we have in our list, we need to give the index +1 as answer. I didnt and I just returend left for any cases so I got that as error

sol

class Solution {
    public int searchInsert(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;

        while (left < right) {
            int mid = left + (right-left)/2;

            if (arr[mid] == target) {
                return mid;  // found
            } else if (arr[mid] < target) {
                left = mid + 1;  // search right
            } else {
                right = mid; // search left
            }
        }
        return (arr[left] < target) ? left + 1 : left;
    }
}

complexity

log n time
1 space

0개의 댓글