One Day Together Leetcode series (i) Title
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.
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
(ii) Problem solving
/* The idea is that if the target number is greater than the maximum number in the vector, the length of the vector is returned, that is, if the target is less than the minimum number in the vector, it returns 0, that is, inserted at the front if the vector range, the binary method is found, If there is an equal to target, return its ordinal, and if not, exit at I=j, return I indicates the target's insertion position * /classSolution { Public:intSearchinsert ( vector<int>& Nums,intTarget) {intLen = Nums.size ();if(Target > nums[len-1])returnLenif(Target < nums[0])return 0;inti =0;intj = len-1; while(I<=J) {intMid = (i+j)/2;if(Nums[mid] = = target)returnMidElse if(Nums[mid]>target) j=mid-1;Elsei = mid+1; }returnI }};
"One Day together Leetcode" #35. Search Insert Position