1.문제
Search Insert Position - LeetCode
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
2.문제설명
이 문제는 주어진 배열에서 target이 들어갈 index의 위치를 반환하는 문제이다.
핵심은 Given a sorted 배열을 준다는 것이다.

3.소스코드
class Solution {
public int searchInsert(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}
}
4.소스코드설명
이분 탐색 을 하기 위해 left 포인터와 right 포인터를 선언 해준다.
mid (left + (right- left) / 2 ) 를 통해 가운데 를 기점으로 찾는다
배열의 가운데를 기준으로 왼쪽과 오른쪽 target이 mid보다 작다면 mid 에서 왼쪽으로 증가 아니라면 오른쪽에서 감소
5.회고
이분탐색에서 대표적인 문제중 하나이다 이런 문제들을 자주 풀었 던 기억이있지만 Python으로 주로 코딩테스트를 준비하여 Java로 풀어내는 부분에서 살짝 생각을 하게 되었다.
'Algorithm' 카테고리의 다른 글
| [leetCode 155] Min Stack (Java) (0) | 2023.08.30 |
|---|---|
| [leetCode 74번] Search a 2D Matrix (Java) (0) | 2023.08.28 |
| [leetCode 141] Linked List Cycle (JAVA) (0) | 2023.08.28 |
| [leetCode 209번] Minimum Size Subarray Sum (Java) (0) | 2023.08.28 |
| [leetCode 167번] Two Sum II - Input Array Is Sorted (Java) (0) | 2023.08.28 |