标签:
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 → 0
public class Solution { public int searchInsert(int[] nums, int target) { if(nums==null || nums.length==0){ return -1; } int res=-1; int len=nums.length; int low=0; int high=len-1; while(low<=high){ int mid=low+(high-low)/2; if(mid==low){ if(target>nums[mid]){ if(target<=nums[high]){ return mid+1; } else{ return high+1; } } else{ return mid; } } else{ if(nums[mid]==target){ return mid; } else if(nums[mid]<target){ low=mid+1; } else{ high=mid-1; } } } return 0; } }
LeetCode-Search Insert Position
标签:
原文地址:http://www.cnblogs.com/incrediblechangshuo/p/5743177.html