"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 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
"Analysis"
This problem is relatively simple, that is, two-point search. The idea is to take the middle each time, if equal to the goal is to return, or according to the size of the relationship cut half. Thus the algorithm complexity is O (logn), Spatial complexity O (1).
"Code"
/********************************** Date: 2015-01-24* sjf0115* title: 35.Search Insert position* URL: Https://oj.leetcode. com/problems/search-insert-position/* Result: ac* Source: leetcode* Blog: **********************************/#include < Iostream> #include <vector>using namespace Std;class solution {public:int searchinsert (int a[], int n, int tar Get) {if (n <= 0) {return-1; }//if int start = 0,end = N-1; Two-point lookup while (start <= end) {int mid = start + ((End-start) >> 1); Target to find if (a[mid] = = target) {return mid; }//if//target in the left half part else if (A[mid] > target) {end = Mid-1; }//else//target in right half else{start = mid + 1; }//else}//while//target element not found then find the insertion position return start;//end + 1}};int main () {solution solution; int a[] = {1,3,5,6}; Intn = 4; int target = 0; int result = Solution.searchinsert (a,n,target); Output cout<<result<<endl; return 0;}
[Leetcode]35.search Insert Position