标签:
class Solution { public: int getfirst(vector<int>& nums,int low,int high,int target) { while(low<=high) { int mid=(low+high)/2; if(nums[mid]==target) { if(mid==0||nums[mid-1]!=target) return mid; else high=mid-1; } else if(nums[mid]>target) high=mid-1; else low=mid+1; } return -1; } int getlast(vector<int>& nums,int low,int high,int target) { while(low<=high) { int mid=(low+high)/2; if(nums[mid]==target) { if(mid==nums.size()-1||nums[mid+1]!=target) return mid; else low=mid+1; } else if(nums[mid]>target) high=mid-1; else low=mid+1; } return -1; } vector<int> searchRange(vector<int>& nums, int target) { vector<int> result(2,-1); if(nums.size()==0) return result; int low=0; int high=nums.size()-1; while(low<=high) { int mid=(low+high)/2; if(nums[mid]==target) { if(mid-1>=0&&nums[mid-1]==target) { int l=getfirst(nums,low,mid-1,target); result[0]=l; } else result[0]=mid; if(mid+1<nums.size()&&nums[mid+1]==target) { int r=getlast(nums,mid+1,high,target); result[1]=r; } else result[1]=mid; break; } else if(nums[mid]>target) high=mid-1; else low=mid+1; } return result; } };
用二分查找法,分别查找重复数字的第一个位置和最后一个位置。
标签:
原文地址:http://www.cnblogs.com/summerkiki/p/5777888.html