Search for a Range
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O (log n ).
If the target is not found in the array, return [-1,-1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
Return [3, 4].
Solution 1:
Use the improved binary search method. The condition for termination is: when left <right-1 ends, there will be two values for our judgment. The biggest advantage of doing so is that you do not have to deal with cross-border issues.
Thanks to teacher Huang for writing such an excellent algorithm: http://answer.ninechapter.com/solutions/search-for-a-range/
Please remember this binary template, which is quite useful.
1. First find the left boundary. When mid = target, move right to mid and continue searching for the left boundary.
If the target is not found, exit.
2. Find the right border. When mid = target, move left to mid and continue searching for the right boundary.
If the target is not found, exit.
1 public class solution {2 Public int [] searchrange (INT [] A, int target) {3 int [] ret = {-1,-1 }; 4 5 if (a = NULL |. length = 0) {6 return ret; 7} 8 9 int Len =. length; 10 int left = 0; 11 int right = len-1; 12 13 // so when loop end, there will be 2 elements in the array.14 // search the left bound.15 while (left <right-1) {16 int mid = left + (right-left)/2; 17 if (target = A [Mid]) {18 // if equal, continue to search for the boundary 19 Right = mid; 20} else if (target> A [Mid]) {21 // move right; 22 left = mid; 23} else {24 Right = mid; 25} 26} 27 28 if (a [left] = target) {29 RET [0] = left; 30} else if (a [right] = target) {31 RET [0] = right; 32} else {33 return ret; 34} 35 36 left = 0; 37 right = len-1; 38 // so when loop end, there will be 2 elements in the array.39 // search the right bound.40 while (left <right-1) {41 int mid = left + (right-left)/2; 42 if (target = A [Mid]) {43 // if equal, continue to the right to find the right boundary 44 left = mid; 45} else if (target> A [Mid]) {46 // move right; 47 left = mid; 48} else {49 right = mid; 50} 51} 52 53 if (a [right] = target) {54 RET [1] = right; 55} else if (a [left] = target) {56 RET [1] = left; 57} else {58 return ret; 59} 60 61 return ret; 62} 63}View code
Leetcode: search for a range problem solving report