[LeetCode] Problem 35 - Search Insert Position

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.

You may assume no duplicates in the array.

Example

No.1

Input: [1,3,5,6], 5

Output: 2

No.2

Input: [1,3,5,6], 2

Output: 1

No.3

Input: [1,3,5,6], 7

Output: 4

No.4

Input: [1,3,5,6], 0

Output: 0

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public int searchInsert(int[] nums, int target) {        
int left = 0;
int right = nums.length - 1;

while (left <= right) {
int middle = (left + right) >> 1;

if (nums[middle] > target)
right = middle - 1;
else if (nums[middle] < target)
left = middle + 1;
else
return middle;
}

return left;
}