Problem:
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would is if it were inserted in order.
Assume no duplicates in the array.
here is 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
Solution: Binary lookup, when not found l=r+1, so according to the last change of L and R to determine the position should be inserted, if the last time is l=mid+1, the location should be inserted into the mid+1, if the last is r=mid-1, then the location should be inserted into the mid , for example, you can draw your own hand.
To give an ordered array and a target integer, it is required to find where the target integer appears in the array, and if not, returns the position of the target integer after the array is inserted.
Java source Code (340MS):
public class Solution {public int searchinsert (int[] nums, int target) { int l=0,r=nums.length-1,pos=0,mid; while (l<=r) { mid= (l+r) >>1; if (Target==nums[mid]) return mid; else if (Target>nums[mid]) { l=mid+1;pos=mid+1; } else{ r=mid-1;pos=mid; } } return pos; }}
C Language Source code (7MS):
int Searchinsert (int* nums, int numssize, int target) { int l=0,r=numssize-1,pos=0,mid; while (l<=r) { mid= (l+r) >>1; if (Nums[mid]==target) return mid; else if (Target>nums[mid]) { l=mid+1;pos=mid+1; } else{ r=mid-1; Pos=mid; } } return POS;}
C + + source code (8MS):
Class Solution {public: int Searchinsert (vector<int>& nums, int target) { int l=0,r=nums.size ()-1, Pos=0,mid; while (l<=r) { mid= (l+r) >>1; if (Nums[mid]==target) return mid; else if (Target<nums[mid]) { r=mid-1;pos=mid; } else{ l=mid+1;pos=mid+1; } } return pos; }};
Python source code (52MS):
Class solution: # @param {integer[]} nums # @param {integer} target # @return {integer} def searchinsert (self, Nums, target): L=0;r=len (nums) -1;pos=0 while l<=r: mid= (l+r) >>1 if target==nums[ Mid]:return mid elif target>nums[mid]:l=mid+1;pos=mid+1 else:r=mid-1;pos=mid return POS
Leetcode Search Insert Position (C,c++,java,python)