Topic:
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.
Thinking Analysis:
Two-point search! The code is also very concise!
C + + Reference code:
class solution {Public :int Searchinsert (intA[], int n, int target) {intbegin=0; IntEnd= N-1; int middle =End/2; while(begin<=End) {middle = (begin+End) /2;if(A[middle] = = target)returnMiddle;Else if(A[Middle] < target)begin= Middle +1;Else End= Middle-1; }return begin;//At this timebegin>End}};
C # Reference Code:
Publicclasssolution{PublicintSearchinsert (int[] A,intTarget) {int begin=0;int End= A.length-1;intMiddle =End/2; while(begin<=End) {middle = (begin+End) /2;if(A[middle] = = target) return middle;Else if(A[middle] < target)begin= Middle +1;Else End= Middle-1; } returnbegin; }}
Leetcode:search Insert Position