본문 바로가기
Problem Solving/LeetCode

[LeetCode] 35. Search Insert Position - Java

by graycode 2026. 5. 18.

 문제 링크

 

Search Insert Position - LeetCode

Can you solve this real interview question? 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 w

leetcode.com

 

 풀이 코드

public class Solution {

    public int searchInsert(int[] nums, int target) {
        int l = 0, r = nums.length - 1, m = r >> 1;
        while (l <= r) {
            if (target <= nums[m]) r = m - 1;
            else l = m + 1;
            m = (r + l) >> 1;
        }

        return l;
    }

}

댓글