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.
Here are few examples.
[1,3,5,6]
, 5 → 2[1,3,5,6]
, 2 → 1[1,3,5,6]
, 7 → 4[1,3,5,6]
, 0 → 0public class Solution { private int searchInsertAux(int[] nums, int target, int l, int r){ if(1 > r - l){ return l; } if(1 == r - l){ if(nums[l] == target){ return l; }else if(nums[l] > target){ return l; }else{ return l+1; } } int m = (l + r) / 2; if(nums[m] > target){ return searchInsertAux(nums, target, l, m); } else if (nums[m] == target){ return m; } else{ // nums[m] < target return searchInsertAux(nums, target, m, r); } } public int searchInsert(int[] nums, int target) { int len = nums.length; return searchInsertAux(nums, target, 0, len); } }
No comments:
Post a Comment