目录
1.搜索旋转排序数组
class Solution {
public:
int search(vector<int>& nums, int target) {
if (nums.size() <= 0)
return -1;
int low = 0;
int high = nums.size() - 1;
while (low < high)
{
int mid = (low + high) / 2;
if (nums[mid] == target)
return mid;
else if (nums[mid] == nums[low] && nums[low] == nums[high])//特殊情况
{
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] == target)
{
return i;
}
}
}
else if (nums[low] <= nums[mid]) //左边有序
{
if (nums[low] <= target && nums[mid] >target)
{
high = mid - 1;
}
else
{
low = mid + 1;
}
}
else //右边有序
{
if (nums[mid] < target && nums[high] >= target)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
}
if (nums[low] == target)
return low;
else
return -1;
}
};
2.在排序数组中查找元素的第一个和最后一个位置
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int>res = { -1, -1 };
int low1 = 0;
int high1 = nums.size();
while (low1 < high1) //查找第一个小于等于target的下标
{
int mid1 = (low1 + high1) / 2;
if (nums[mid1] >= target)
{
high1 = mid1;
}
else
{
low1 = mid1 + 1;
}
}
int low2 = 0;
int high2 = nums.size();
while (low2 < high2) //查找第一个大于target的下标
{
int mid2 = (low2 + high2) / 2;
if (nums[mid2] <= target)
{
low2 = mid2 + 1;
}
else
{
high2 = mid2;
}
}
if (low1 < nums.size() && nums[low1] == target) //注意:low1可能大于nums.size()
{
res[0] = low1;
}
if (low2 > 0 && nums[low2 - 1] == target)
{
res[1] = low2 - 1;
}
return res;
}
};