LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
📌- 풀이
- start와 end를 각각 설정하고
- start가 end 보다 작거나 같을 동안 반복
- 중간값을 설정하고 중간값 보다 큰지 작은지 확인해서
- 인덱스를 찾아내고 출력
이분 탐색 문제가 나중에 갈수록 점점 더 어려워져서 안 풀게 되는 것 같아서, 정리를 한번 하고 넘어가야 될 것 같다.
🔥 - Java 코드
class Solution {
public int searchInsert(int[] nums, int target) {
int start = 0;
int end =nums.length-1;
int mid=0;
while(start <= end){
mid = (start+end)/2;
if(nums[mid] <target){
start = mid +1;
}else if(nums[mid] >target){
end = mid -1;
}else{
return mid;
}
}
if(nums[mid] >target){
return mid;
}else{
return mid+1;
}
}
}