Search for a Range

class Solution {
public:
	vector<int> searchRange(vector<int>& nums, int target) {
		vector<int> result;
		int tmp = 0;
		int left = 0, right = nums.size(), mid = 0;
		//if (left == right) return nums[0] == target ? vector<int>{0, 0} : vector<int>{ -1, -1 };
		while (left<right){
			mid = (left + right) / 2;
			if (nums[mid] == target){
				tmp = mid;
				while (mid>0&&nums[mid - 1] == target) mid--;
				while (tmp<nums.size()-1&&nums[tmp + 1] == target) tmp++;
				return vector<int> {mid, tmp};
			}
			else if (nums[mid]<target){
				left = mid + 1;
			}
			else{
				right = mid;
			}

		}
		return vector<int> {-1, -1};
	}
};

阅读更多
文章标签: leetcode
个人分类: leetcode
上一篇Search in Rotated Sorted Array
下一篇Search Insert Position
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭