显然是二分,关键在于怎么处理mid,+1,-1的微妙处。
cpp实现:
#include#include using namespace std; // @lc code=start class Solution { public: vector searchRange(vector & nums, int target) { if (nums.size()==0){ return vector {-1,-1}; } int low = lowerFound(nums,target); int high = upperFound(nums,target); if (low<0 || low>=nums.size()){ // 越界 low = -1; }// 值不相等 else if (nums[low]!=target) low=-1; if (high<0 || high>=nums.size()){ // 越界 high = -1; } // 值不相等 else if (nums[high]!=target) high=-1; return vector {low,high}; } int lowerFound(vector & nums, int target){ int left=0, right=nums.size()-1; while(left target){ // 在左边 right = mid-1; } } cout<<"left: "< nums, int target){ int left=0, right=nums.size()-1; while(left target){ // 在左边 right = mid-1; } } if (nums[left]==target){ // 如果是[7,7,7],7这种情况 return left; } cout<<"high: "<
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)