[LeetCode][Java] Search Insert Position

최지수·2021년 11월 28일
0

Algorithm

목록 보기
30/77
post-thumbnail

문제

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(logn)O(log n) runtime complexity.

제한사항

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

접근

이진 탐색을 구현하라는 문제였습니다.

여기에 추가로, 존재하지 않는다면 정렬이 유지된 상태로 적절하게 배치할 수 있는 인덱스를 반환해야합니다.

이 경우는 mid 값을 지속적으로 업데이트하면서 nums[mid] 값이 target보다 작을 경우 mid+1을, 아니면 그대로 mid 값을 반환시키면 됩니다.

답안

class Solution {
    public int searchInsert(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        int mid = 0;
        while(left <= right){
            mid = (left + right) >> 1;
            if(nums[mid] < target){
                left = mid + 1;
            } else if(nums[mid] > target){
                right = mid - 1;
            } else{
                break;
            }
        }
        if(nums[mid] < target)
            ++mid;
        return mid;
    }
}
profile
#행복 #도전 #지속성

0개의 댓글