题目链接:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
题意:给你一个有序数组和一个target值,让求target值出现的第一次位置和最后一次位置。
分析:二分很明显,不过我自己的方法只是二分查找target值,随便找到一个target值之后遍历周围获得位置,而题解方法要巧妙很多:
找leftIdx即为在数组中寻找第一个大于等于target的下标,寻找rightIdx即为在数组中寻找第一个大于target的下标,然后将下标减一。
先是我的菜鸡代码
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int n=nums.size(); vector<int> ans(2); ans[0]=-1,ans[1]=-1; int l=0,r=n-1; while(l<=r){ int mid=(l+r)/2; //cout<<l<<" "<<r<<" "<<mid<<endl; if(nums[mid]<target){ l=mid+1; }else if(nums[mid]>target){ r=mid-1; }else if(nums[mid]==target){ ans[0]=mid,ans[1]=mid; while((ans[0]-1)>=0&&nums[ans[0]-1]==nums[mid])ans[0]-=1; while((ans[1]+1)<n&&nums[ans[1]+1]==nums[mid])ans[1]+=1; break; } } return ans; } };
题解的:
class Solution { public: int binarySearch(vector<int>& nums, int target, bool lower) { int left = 0, right = (int)nums.size() - 1, ans = (int)nums.size(); while (left <= right) { int mid = (left + right) / 2; if (nums[mid] > target || (lower && nums[mid] >= target)) { right = mid - 1; ans = mid; } else { left = mid + 1; } } return ans; } vector<int> searchRange(vector<int>& nums, int target) { int leftIdx = binarySearch(nums, target, true); int rightIdx = binarySearch(nums, target, false) - 1; if (leftIdx <= rightIdx && rightIdx < nums.size() && nums[leftIdx] == target && nums[rightIdx] == target) { return vector<int>{leftIdx, rightIdx}; } return vector<int>{-1, -1}; } };