The 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
My Analysis:
The question has already assumed ther is no duplicates in the array. In reality, we should take care of This Case!The key idea behind ThisSolution is to use invariant That:before we exit from the whileLoop, the target must meet the Condition:a[front] < target <B[end]when We exit from the whileloop, only conditions is possible:1. The target is successfully found out.2. The front pointer move beyond the end pointer, or the end pointer move before the front pointer. Note:the mid Pointer now in the position when front= = end. (The latest position formid) A.ifFront pointer move beyond the end pointer, means the target larger than the last mid, it should is palced after the Right, last mid. B.ifEnd pointer move before the front pointer, means the target smaller than the last mid, it should is palced at the Mid ' s position (not before mid:mid-1), all elements (includ mid) should is move backward one node.The stop State:end< target <Front, the position to insert target is front. Before reaching theFinalstate:[elements smaller than target], front (mid), end, [elements larger than Target]iff mid<Target, we forward front one step. [Elements smaller than target],element smaller than target, front (mid) end, [elements larger than target]2.1 Iff Mid <Target, we forward front one step. Now front are pointing at the first element Thisis larger than target.2.2 IFF Mid >Target, we bacward end one step. Now front keep the same, pointing at the first element, which is larger than target.
The solution:
Public classSolution { Public intSearchinsert (int[] A,inttarget) { if(A.length = = 0) return-1; intFront = 0; intEnd = A.length-1; intMID =-1; while(Front <=end) {Mid= (front + end)/2; if(A[mid] = =target) { returnmid; } Else if(A[mid] <target) {Front= Mid + 1; } Else{End= Mid-1; } } returnFront; }}
[Leetcode#35] Search Insert Position