class Solution {
public:
int search(vector<int>& nums, int target) {
int left=0;
int right = nums.size()-1;
while(left<=right)
{
int mid = (left+right)/2;
//1.nums[mid] > target
if(nums[mid]>target)
right = mid-1;
//2.nums[mid] < target
else if(nums[mid]<target)
left = mid+1;
//3.nums[mid] == target
else
return mid;
}
return -1;
}
};
特殊情况:
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int left = 0;
int right = nums.size()-1;
//处理边界情况
if(nums.size() == 0)
return {-1,-1};
//1.确定左端点:
while(left<right)
{
int mid = left + (right-left)/2;
if(nums[mid] < target) left = mid+1;
else if(nums[mid] >= target) right = mid;
}
if(nums[left]!=target) return {-1,-1};
int begin = left;
//2.确定右端点:
left=0,right=nums.size()-1;
while(left<right)
{
int mid = left+(right-mid+1)/2;
if(nums[mid] <= target) left = mid;
else if(nums[mid] > target) right = mid-1;
}
int end = left;
return {begin,end};
}
};
找左端点:
找右端点:
class Solution {
public:
int mySqrt(int x) {
if(x==0)
return 0;
long long left = 1;
long long right = x;
while(left<right)
{
long long mid = left + (right - left + 1)/2;
if((mid*mid) <= x) left = mid;
else right = mid -1;
}
return left;
}
};
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int left = 0;
int right = nums.size()-1;
if(nums.size() == 1)
{
if(target > nums[0])
return 1;
if(target <= nums[0])
return 0;
}
while(left < right)
{
int mid = left + (right - left)/2;
if(nums[mid] < target) left = mid+1;
else right = mid;
}
if(nums[right] < target) return right + 1;
return right;
}
};
class Solution {
public:
int peakIndexInMountainArray(vector<int>& arr) {
int left=0,right=arr.size()-1;
while(left<right)
{
int mid = left + (right-left +1)/2;
if(arr[mid-1] < arr[mid]) left=mid;
else right = mid -1;
}
return left;
}
};
class Solution {
public:
int findPeakElement(vector<int>& nums) {
int left=0,right=nums.size()-1;
while(left<right)
{
int mid = left + (right - left + 1)/2;
if(nums[mid-1] < nums[mid]) left = mid;
else right = mid-1;
}
return left;
}
};
class Solution {
public:
int findMin(vector<int>& nums) {
int left = 0, right = nums.size() - 1;
int n = nums[right];
while (left < right)
{
int mid = left + (right - left) / 2;
if (nums[mid] > n) left = mid + 1;
else right = mid;
}
return nums[right];
}
};
class Solution {
public:
int takeAttendance(vector<int>& records) {
int left = 0 , right = records.size()-1;
while(left < right)
{
int mid = left + (right - left)/2;
if(mid == records[mid]) left = mid +1;
else right = mid;
}
if(records[left] == left)
return left+1;
return left;
}
};