This topic is still belong to the title of the search class, similar to the previous topic, the title of the request is given a target, in an ordered array to find the insertion order of the element, if present, return the element's subscript. This problem is more intuitive, so it is easier to do hands, it should be noted that the boundary conditions, such as:
(1). The target element is smaller than the smallest element in the sorted array
(2). The target element is larger than the largest element in the sorted array
Please look at the code, the code is still relatively clear
Class Solution {public: int Searchinsert (vector<int>& nums, int target) { int len = Nums.size (); if (len = = 0) {return 0;} int left = 0;int right = Len-1;int mid = 0;if (Target > Nums[right]) {return right + 1;} while (left < right) {mid = left + (right-left)/2;if (nums[left] = = target) {return left;} if (nums[right] = = target) {return right;} if (nums[mid] = = target) {return mid;} if (Nums[mid] > target) {right = mid;} Else{left = mid + 1;}} return left; }};
Written question 48. Leetcode OJ (35)