标签:
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]
.
本题利用二分算法的思想,寻找target的开始和结束位置。时间:17ms。代码如下:
class Solution { public: int searchfRange(vector<int>& nums, int f, int l, int target){ if (f > l || nums[l] != target) return l + 1; if (nums[f] == target) return f; int mid = f + (l - f) / 2; if (nums[mid] == target) return searchfRange(nums, f, mid - 1, target); else return searchfRange(nums, mid + 1, l, target); } int searchlRange(vector<int>& nums, int f, int l, int target){ if (f > l || nums[f] != target) return f - 1; if (nums[l] == target) return l; int mid = f + (l - f) / 2; if (nums[mid] == target) return searchlRange(nums, mid + 1, l, target); else return searchlRange(nums, f, mid - 1, target); } vector<int> searchRange(vector<int>& nums, int f, int l, int target){ if (f > l || target < nums[f] || target > nums[l]) return vector<int>(2, -1); vector<int> range(2,-1); int mid = f + (l - f) / 2; if (nums[f] == target){ range[0] = f; range[1] = searchlRange(nums, f+1, l, target); return range; } if (nums[l] == target){ range[0] = searchfRange(nums, f, l-1, target); range[1] = l; return range; } if (nums[mid] == target){ range[0] = searchfRange(nums, f, mid - 1, target); range[1] = searchlRange(nums, mid + 1, l, target); return range; } else if (nums[mid] < target) return searchRange(nums, mid + 1, l, target); else return searchRange(nums, f, mid - 1, target); } vector<int> searchRange(vector<int>& nums, int target) { if (target<nums.front() || target>nums.back()) return vector<int>(2, -1); return searchRange(nums, 0, nums.size() - 1, target); } };
[LeetCode] #34 Search for a Range
标签:
原文地址:http://www.cnblogs.com/Scorpio989/p/4579279.html