leetcode: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]
.
分析:题意为在一个有序数组中找到给定目标值的起始位置并返回,如果目标值不存在则返回[1,1].
思路:使用binarySearchLow()去找到不小于目标值数字的最小索引,使用binarySearchUp()去找到不大于目标值数字的最大索引,然后即可得到索引范围。
code如下:
class Solution { private: int binarySearchLow(vector<int>& nums, int target, int begin, int end) { if(begin > end) return begin; int mid = begin + (end - begin) / 2; if(nums[mid] < target) return binarySearchLow(nums, target, mid + 1, end); else return binarySearchLow(nums, target, begin, mid - 1); } int binarySearchUp(vector<int>& nums, int target, int begin, int end) { if(begin > end) return end; int mid = begin + (end - begin) / 2; if(nums[mid] > target) return binarySearchUp(nums, target, begin, mid - 1); else return binarySearchUp(nums, target, mid + 1, end); } public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> res(2, -1); if(nums.empty()) return res; int high = binarySearchUp(nums, target, 0, nums.size() -1); int low = binarySearchLow(nums, target, 0, nums.size() - 1); if(high >= low) { res[0] = low; res[1] = high; return res; } return res; } };
其他方法:先找到有序数组中与目标值相同的数字的位置,然后检查其个数.
code:
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int low=0; int high=nums.size()-1; vector<int> ans(2,-1); int flag=-1; //数组中是否存在与目标值相同数字的标志 int start,end; while(low<=high){ int mid=(low+high)/2; if(nums[mid]<target){ low=mid+1; } else if(nums[mid]>target){ high=mid-1; } else{ flag=mid; break; } } if(flag!=-1){ start=flag; while(start>=0 && nums[start]==target){ start--; } ans[0]=start+1; end=flag; while(end < nums.size() && nums[end]==target){ end++; } ans[1]=end-1; } return ans; } };
其他解法:解决问题的短代码(使用迭代器)
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> ret; vector<int>::iterator start = find(nums.begin(), nums.end(), target); vector<int>::reverse_iterator end = find(nums.rbegin(), nums.rend(), target); ret.push_back( (start == nums.end() ? -1 : start-nums.begin() ) ),ret.push_back(nums.size() - 1 - (end - nums.rbegin())); return ret; } };
python:
class Solution(object): def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ if target not in nums: return ([-1,-1]) low = nums.index(target) nums.sort(reverse=True) high = len(nums)-nums.index(target)-1 result = [] result.append(low) result.append(high) return (result)
朱颜辞镜花辞树,敏捷开发靠得住!