"title"
Given a sorted array of integers, find the starting and ending position of a Given target value.
Your algorithm ' s runtime complexity must is in the order of O(log n).
if The target is not a found in the array, Return [-1,-1] .
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
Return [3, 4] .
"Analysis"
This is a binary lookup of the deformation, the use of two binary search can be achieved, the first time is to find the target element of the continuous minimum position, the second is to find the target element of the continuous maximum position.
So the time complexity of the algorithm is still O (Logn), the spatial complexity is O (1)
For specific reference: [Classic face question] two points to find the problem summary
"Code"
/********************************** Date: 2015-01-24* sjf0115* title: 34.Search for a range* URL: https://oj.leetcode.com/ problems/search-for-a-range/* Result: ac* Source: leetcode* Blog: **********************************/#include <iostream># Include <vector>using namespace Std;class solution {public:vector<int> searchrange (int a[], int n, int tar Get) {vector<int> result; if (n <= 0) {return result; }//if//The minimum position of the target element int left = Searchstartrange (A,n,target); The maximum position of the target element int right = Searchendrange (A,n,target); Result.push_back (left); Result.push_back (right); return result; }private://The minimum position of the target element int searchstartrange (int a[],int n,int target) {int start = 0,end = N-1; while (start <= end) {int mid = (start + end)/2; The target is the intermediate element if (a[mid] = = target) {//If the element to the left of the middle element equals the target element if (mid-1 >= 0 &&amP A[MID-1] = = target) {end = Mid-1; }//if else{return mid; }}//target is in the right half part else if (A[mid] < target) {start = mid + 1; }////target in left half else{end = mid-1; }}//while return-1; }//The maximum position of the target element int searchendrange (int a[],int n,int target) {int start = 0,end = N-1; while (start <= end) {int mid = (start + end)/2; The target is the intermediate element if (a[mid] = = target) {//If the element to the right of the middle element equals the target element if (Mid + 1 < n && A[mid + 1] = = target) {start = mid + 1; }//if else{return mid; }}//target is in the right half part else if (A[mid] < target) {start = mid + 1; }////target in left half else{end = Mid-1; }}//while return-1; }};int Main () {solution solution; int a[] = {1}; int n = 1; int target = 0; vector<int> result = Solution.searchrange (a,n,target); Output for (int i = 0;i < Result.size (); ++i) {cout<<result[i]<<endl; }//for return 0;}
[Leetcode]34.search for a Range