Skip to content

Commit a4193a4

Browse files
committed
[Easy] Title: 35. Search Insert Position - LeetCode
1 parent d448214 commit a4193a4

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# [Easy] 35. Search Insert Position
2+
3+
[문제 링크](https://leetcode.com/problems/search-insert-position/)
4+
5+
### 문제 설명
6+
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.
7+
8+
You must write an algorithm with `O(log n)` runtime complexity.
9+
10+
### 입출력
11+
**Example 1:**
12+
13+
```
14+
Input: nums = [1,3,5,6], target = 5
15+
Output: 2
16+
```
17+
18+
**Example 2:**
19+
20+
```
21+
Input: nums = [1,3,5,6], target = 2
22+
Output: 1
23+
```
24+
25+
**Example 3:**
26+
27+
```
28+
Input: nums = [1,3,5,6], target = 7
29+
Output: 4
30+
```
31+
32+
### 제약조건
33+
- `1 <= nums.length <= 104`
34+
- `104 <= nums[i] <= 104`
35+
- `nums` contains **distinct** values sorted in **ascending** order.
36+
- `104 <= target <= 104`
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
public int searchInsert(int[] nums, int target) {
3+
int left = 0; int right = nums.length - 1;
4+
5+
while(left <= right) {
6+
int mid = (left + right) / 2;
7+
8+
if(nums[mid] == target) {
9+
return mid;
10+
} else if(nums[mid] < target) {
11+
left = mid + 1;
12+
} else {
13+
right = mid - 1;
14+
}
15+
}
16+
return left;
17+
}
18+
}

0 commit comments

Comments
 (0)