852.山脉数组的峰顶索引
一、题目描述
即下标 i 前的所有元素都升序、后的所有元素都降序, i 是最大值
OJ题目链接:力扣(LeetCode)
二、思路解析
三、代码
class Solution {
public:
int peakIndexInMountainArray(vector<int>& arr)
{
int left = 0, right = arr.size() - 1;
while (left < right)
{
int mid = left + (right - left) / 2;
if (arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]) return mid;
else if (arr[mid] < arr[mid + 1]) left = mid + 1;
else right = mid;
}
return -1;
}
};
162.寻找峰值
一、题目描述
即找区间内的任意一个极大值
注意这句话!
二、思路解析
三、代码
class Solution {
public:
int findPeakElement(vector<int>& nums)
{
int left = 0, right = nums.size() - 1;
while (left < right)
{
int m = left + (right - left) / 2;
if(nums[m] < nums[m + 1]) left = m + 1;
else right = m;
}
return left;
}
};
153.寻找旋转排序数组中的最小值
一、题目描述
OJ题目链接:力扣(LeetCode)
二、思路解析
三、代码
class Solution {
public:
int findMin(vector<int>& nums)
{
int left = 0, right = nums.size() - 1, n = right;
while (left < right)
{
int mid = left + (right - left) / 2;
if (nums[mid] > nums[n]) left = mid + 1;
else right = mid;
}
return nums[left];
}
};
LCR 173.点名
一、题目描述
OJ题目链接:力扣(LeetCode)
二、思路解析
三、代码
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;
}
return left == records[left] ? left + 1 : left;
}
};