
[문제]
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.
https://leetcode.com/problems/search-insert-position/?envType=study-plan-v2&envId=top-interview-150
class Solution {
public int searchInsert(int[] nums, int target) {
int s = 0;
int e = nums.length - 1;
int mid = 0;
while (s <= e) {
mid = (s + e) / 2;
if (nums[mid] < target) { // 타겟보다 작은경우,
s = mid + 1;
} else if (nums[mid] > target) { // 타겟보다 큰 경우
e = mid - 1;
} else { // 타겟과 일치하는 경우
return mid;
}
}
return s;
}
}
// 0 3 - 1
// 2 3 - 2
// 3 3 - 3
// 4 3 -
주어진 배열 nums에 target이 존재하는지 탐색하는 문제이다. O(log n)의 시간복잡도로 해결해야하기 때문에 이분탐색을 활용하였다.