# leetcode34. Find First and Last Position of Element in Sorted Array

2021/8/20 17:37:06 浏览：

1.如果first和last下标都是-1，说明在此之前没有找到这个数。那么现在我们找到了就需要更新first和last为mid。

2.不然的话，我们只需要把first和mid，last与mid进行比较，然后替换就可以了。

``````class Solution {
public:
vector<int>ans;
void binarySearch(vector<int>& nums, int target, int low, int high) {
if (low > high) return; //记得跳出循环哦。
int mid = (low + high) >> 1;
if (nums[mid] == target) { // 中间值为target的情况哦。
if (ans[0] == -1 && ans[1] == -1) ans[0] = ans[1] = mid;
else {
if (ans[0] > mid) ans[0] = mid;
if (ans[1] < mid) ans[1] = mid;
}
/*千万别停止搜索，给我接着搜*/
binarySearch(nums, target, low, mid - 1);
binarySearch(nums, target, mid + 1, high);
}
/*中间不是就可以找一边了，中间是要找两边哦*/
else if (nums[mid] > target) binarySearch(nums, target, low, mid - 1);
else binarySearch(nums, target, mid + 1, high);
return;
}
vector<int> searchRange(vector<int>& nums, int target) {
ans = { -1,-1 };
if (nums.size() == 0 || nums[0] > target || nums[nums.size() - 1] < target)
return { -1,-1 };
binarySearch(nums, target, 0, nums.size() - 1);
return ans;
}
};
``````

``````class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> ans = { -1,-1 };
if (nums.size() == 0 || nums[0] > target || nums[nums.size() - 1] < target
|| binary_search(nums.begin(), nums.end(), target) == 0)
return { -1,-1 };
ans[0] = lower_bound(nums.begin(), nums.end(), target) - nums.begin();
ans[1] = upper_bound(nums.begin(), nums.end(), target) - nums.begin() - 1;
return ans;
}
};
``````

upper_bound(起始地址，结束地址，val)

``````class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> ans = { -1,-1 };
if (nums.size() == 0 || nums[0] > target || nums[nums.size() - 1] < target
|| binary_search(nums.begin(), nums.end(), target) == 0)/*这个函数是看nums里有没有这个数，*/
return { -1,-1 };
ans[0] = lower_bound(nums.begin(), nums.end(), target) - nums.begin();
ans[1] = upper_bound(nums.begin(), nums.end(), target) - nums.begin() - 1;
return ans;
}
};
``````