Created
February 19, 2013 14:32
-
-
Save pdu/4986412 to your computer and use it in GitHub Desktop.
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]. http://leetcode.com/onlinejudge#question_34
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution { | |
| public: | |
| vector<int> searchRange(int A[], int n, int target) { | |
| int left = 0, right = n - 1; | |
| int ans1 = n; | |
| while (left <= right) { | |
| int mid = (left + right) >> 1; | |
| if (A[mid] == target) { | |
| ans1 = min(ans1, mid); | |
| right = mid - 1; | |
| } | |
| else if (A[mid] > target) | |
| right = mid - 1; | |
| else | |
| left = mid + 1; | |
| } | |
| ans1 = ans1 == n ? -1 : ans1; | |
| int ans2 = -1; | |
| left = 0, right = n - 1; | |
| while (left <= right) { | |
| int mid = (left + right) >> 1; | |
| if (A[mid] == target) { | |
| ans2 = max(ans2, mid); | |
| left = mid + 1; | |
| } | |
| else if (A[mid] > target) | |
| right = mid - 1; | |
| else | |
| left = mid + 1; | |
| } | |
| vector<int> ans; | |
| ans.push_back(ans1); | |
| ans.push_back(ans2); | |
| return ans; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment