思路:
遍历数组,碰到第一个元素等于目标值时,就是起始位置,每次更新终点位置(数组元素等于目标值的终点位置)
不过这是一种trivial的解法(虽然能够被accept),题目要求时间复杂度是O(log n),所以必须是二分法。
二分法分两步,首先找到最左边的目标值,然后找到最右边的坐标值,最后汇总一下就可以了。
trivial code:
class Solution { public: vector<int> searchRange(int A[], int n, int target) { vector<int> ret; int lastIndex = 0; bool flag = false; for(int i = 0;i < n;i++) if(A[i] == target){ if(!flag) ret.push_back(i); lastIndex = i; flag = true; } if(!flag){ ret.push_back(-1); ret.push_back(-1); } else ret.push_back(lastIndex); return ret; } };
二分法code:
class Solution { public: int binaryLeftSearch(int A[],int left,int right,int target){ int originalLeft = left, originalRight = right; while(left <= right){ int mid = (left + right)/2; if(A[mid] == target){ if(mid == originalLeft || A[mid-1] != target) return mid; else right = mid-1; } else if(A[mid] > target) right = mid - 1; else left = mid + 1; } return -1; } int binaryRightSearch(int A[],int left,int right,int target){ int originalLeft = left, originalRight = right; while(left <= right){ int mid = (left + right)/2; if(A[mid] == target){ if(mid == originalRight || A[mid+1] != target) return mid; else left = mid+1; } else if(A[mid] > target) right = mid - 1; else left = mid + 1; } return -1; } vector<int> searchRange(int A[], int n, int target) { vector<int> ret(2); ret[0] = binaryLeftSearch(A,0,n-1,target); ret[1] = binaryRightSearch(A,0,n-1,target); return ret; } };