# leetcode34——Search for a Range

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> ans;
int start = -1, end = -1;
for (int i = 0;i < nums.size();i++) {
if (nums[i] == target) {
end = i;
if (start == -1)
start = i;
}
else if (nums[i] > target) {
ans.push_back(start);
ans.push_back(end);
return ans;
}
}
ans.push_back(start);
ans.push_back(end);
return ans;
}

};

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

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120