34 Search for a Range(目标数的范围Medium)
题目意思:递增数组,找到目标数的范围,找不到则返回[-1,-1]
思路:折半查找
1 class Solution { 2 public: 3 vector<int> searchRange(vector<int>& nums, int target) { 4 int start=0,end=nums.size()-1; 5 vector<int> ans; 6 while(start<=end){ 7 int temp=(start+end)/2; 8 if(nums[temp]>target){ 9 end=temp-1; 10 } 11 else if(nums[temp]<target){ 12 start=temp+1; 13 } 14 else if(nums[temp]==target){ 15 int flag1=temp,flag2=temp; 16 while(flag1>0&&nums[flag1-1]==target){ 17 --flag1; 18 } 19 while(flag2<nums.size()-1&&nums[flag2+1]==target){ 20 ++flag2; 21 } 22 ans.push_back(flag1); 23 ans.push_back(flag2); 24 return ans; 25 } 26 } 27 ans.push_back(-1); 28 ans.push_back(-1); 29 return ans; 30 } 31 };
时间复杂度:O(logn)
运行时间:12ms
代码太冗余了,以后再精简吧