[코테 풀이] Search Insert Position

시내·2024년 6월 4일

Q_35) Search Insert Position

출처 : https://leetcode.com/problems/search-insert-position/

Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You must write an algorithm with O(log n) runtime complexity.

class Solution {
    public  int searchInsert(int[] nums, int target) {
        return binarySearch(nums, target, 0, nums.length - 1);
    }

    public  int binarySearch(int[] nums, int key, int low, int high) {
        if (low <= high) {
            int mid = (low + high) / 2;
            if (key == nums[mid]) {
                return mid;
            } else if (key < nums[mid]) {
                if (mid - 1 >= 0) {
                    if (key > nums[mid - 1]) {
                        return mid;
                    }
                }
                else{
                    return 0;
                }
                return binarySearch(nums, key, low, mid - 1);
            } else if (key > nums[mid]) {
                if (mid + 1 <= nums.length-1) {
                    if (key < nums[mid + 1]) {
                        return mid + 1;
                    }
                }
                else{
                    return nums.length;
                }
                return binarySearch(nums, key, mid + 1, high);
            }
        }
        return -1;
    }
    
}

💫 O(log n)이 포인트였던 문제!
-> binary search 활용

profile
contact 📨 ksw08215@gmail.com

0개의 댓글