LeetCode 35: Search Insert Position
Problem Description
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 write an algorithm with O(log n)
runtime complexity.
Example 1
Input: nums = [1,3,5,6], target = 5
Output: 2
Example 2
Input: nums = [1,3,5,6], target = 2
Output: 1
Solution
The problem basically asks when we do a binary search to look for a target
, if the target
is not in the nums
, what values l
and r
pointers refer to? It turns out: nums[r]<target<nums[l]
.
Java Code
class Solution {
public int searchInsert(int[] nums, int target) {
int len=nums.length, l=0, r=len-1, mid;
while( l <= r){
mid = (l+r) / 2;
if(target == nums[mid]) return mid;
if( target > nums[mid]) l=mid+1;
else r = mid-1;
}
return l;
}
}
The post is published under CC 4.0 License.