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
Problem: Given a sorted array and an integer, if an integer is already in the array, the subscript in the array is returned, otherwise the position should be inserted.
To search a sorted array, it is natural to think of binary search, after all, a classic scenario. This problem is also really a binary search of a simple application.
The reason to record this problem is to feel the binary search and the previous two-pointer pointers, or the sliding window algorithm (sliding windows) somewhat similar.
Binary search, in fact, can be understood as the sliding window algorithm that is halved each time to locate the final target position.
While the sliding window algorithm, another typical scenario is to solve the maximum/minimum continuous sub-array, or continuous substring. In another Boven introduction: Minimum Size subarray Sum.
1 intSearchinsert (vector<int>& Nums,inttarget) {2 3 if(nums.size () = =0) {4 return 0;5 }6 7 if(nums.size () = =1) {8 return(nums[0] < target)?1:0;9 }Ten One A intL =0; - intR = (int) Nums.size ()-1; - the while(L <r) { - - if(L +1==r) { - if(Target <=Nums[l]) { + returnl; - } + Else if(Target <=Nums[r]) { A returnR; at } - Else{ - returnr+1; - } - } - in intMid = (L + r)/2; - to if(Nums[mid] = =target) { + returnmid; - } the * if(Nums[mid] <target) { $L =mid;Panax Notoginseng}Else{ -R =mid; the } + } A the //actually cannot execute here, there must be a return in front. + return 0; -}
[Leetcode] 35. Search Insert Position Solution Ideas