본문 바로가기
LeetCode

[LeetCode] 35. Search Insert Position

by JungSeung 2023. 11. 1.
728x90

https://leetcode.com/

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.


Example 1:

nput: nums = [1,3,5,6], target = 5
Output: 2

 

Example 2:

Input: nums = [1,3,5,6], target = 2
Output: 1

Example 3:

Input: nums = [1,3,5,6], target = 7
Output: 4

 

Constraints:

  • 1 <= nums.length <= 10^4
  • -10^4 <= nums[i] <= 10^4
  • nums contains distinct values sorted in ascending order.
  • -10^4 <= target <= 10^4

Solutions Code :

var searchInsert = function(nums, target) {
    let left = 0;
    let right = nums.length - 1;

    while (left <= right) {
        const mid = Math.floor((left + right) / 2);

        if (nums[mid] === target) {
            return mid; // target을 찾은 경우 해당 인덱스 반환
        } else if (nums[mid] < target) {
            left = mid + 1; // 중간 값보다 큰 경우 오른쪽 부분 탐색
        } else {
            right = mid - 1; // 중간 값보다 작은 경우 왼쪽 부분 탐색
        }
    }

    // while 루프를 빠져나왔을 때 left가 삽입 위치가 됨
    return left;
};

 

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90