Skip to content

Commit 6dd827c

Browse files
committed
add solution of problem 35: search insert position
1 parent 3fec98b commit 6dd827c

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

SearchInsertPosition35/README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
Given a sorted array 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.
2+
3+
You may assume no duplicates in the array.
4+
5+
Here are few examples.
6+
`[1,3,5,6]`, 5 → 2
7+
`[1,3,5,6]`, 2 → 1
8+
`[1,3,5,6]`, 7 → 4
9+
`[1,3,5,6]`, 0 → 0
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
public class Solution {
2+
public int searchInsert(int[] nums, int target) {
3+
if (nums == null || nums.length == 0)
4+
return 0;
5+
6+
int left = 0;
7+
int right = nums.length - 1;
8+
9+
while (left <= right) {
10+
int mid = (left + right) >> 1;
11+
if (nums[mid] > target)
12+
right = mid - 1;
13+
else if (nums[mid] < target)
14+
left = mid + 1;
15+
else
16+
return mid;
17+
}
18+
19+
return left;
20+
}
21+
}

0 commit comments

Comments
 (0)