这是我参加8月更文应战的第10天,活动概略检查:8月更文应战

思路

首要一个区间分为两个,然后将答案承认在某个区间中,删掉另一个区间,这样每次就可以将答案规模缩小一半。

element什么意思分的流程

  1. 承认二分的间隔
  2. 编写二分的代码结构
  3. 规划一个check
  4. 判别一下区间怎样更新
  5. 如果更新方法是l=mid, r = mid – 1,运用模版二,在算mid的时分加1

模版一

当我们将区间[l, r]差异红[l, mid]和[mid + 1, r]时,其更新操作是r = mid或者l = mid + 1;,核算mid时不需求加1。

C++ 代码模板:

int bsearch_1(int l, int r)
{
while (l < r)
{
int mid = l + r >> 1;elementary
if (check(mleetcode是什么id)) r = mid;
else l = mid + 1;
}
return l;
}

模版二

当我们将区间[l, r]差异红[lelementary, mid – 1]和[mid, r]时,其更新操作是r = mid – 1或者l = mid;,此刻leetcode官网为了防LeetCode止死循环,核算mid时需求加1。

C++ 代码模板:

int bsearch_2(int l, int r)
{
while (l < r)
{
int mid = l + r + 1 >> 1;
if (check(miapplicationd)) l = mid;
else r = mid - 1;
}
return l;
}

相关标题列表

  • 69. Sqrt(xappearance)

运用模版二,原因是所appear求的mid契合app下载的条件是mid*mid <= x的时分,差异的区间是[l, mid – 1]和[mid, r],落到了后一个区间中。

class Solution {
public:
int mySqrt(int x) {
int l = 0, r = x;
while (l < r)
{
long long midelement是什么牌子 = l + r + 1ll >> 1;
if (midLeetCode <= x / mid ) l = mid;
else r = mid - 1LeetCode;
}
return l;
}
};
  • 35. Searelement是什么牌子ch Insert PoElementsition

运用模版一,nums[mid] >= target所得的mid是要取的,所以差异为[l, mid]

clappleass Solution {
pubapplicationlic:
int searchInsertleetcode题库(vector<int>&amleetcode题库p; nums,element翻译 int target) {
int l = 0, r = nums.size();
while(l < r) {
int mid = l + r >> 1;
if(nums[mid] >= target) r = mid;
else l = mid + 1;app下载
}
retleetcode题库urn l;
}
};
  • 34. Find First and Last Positioelement什么意思n of Element in Soelement翻译rted Array

两个模版的运用

claappearancess Solution {
public:
vector<int> searchRangeelementary(vector<int>& nums, int target) {
int l = 0,r = nums.size();
while(l < r){
int mid = l + r >> 1;
if(nelementanimationums[mid] >= target) r = mid;
eelementarylseappear l = mid + 1;
}
if(l == nums.size() || nums[l] != targeappeart) return {-1,-1};
int left = l;
l = 0,r =elements nums.size()-1;
while(l < r){
int mid = l + r + 1 >> 1;
if(nums[mid] <= target) l = mid;
else r = mid - 1;
}
return {left,leetcode下载l}appstore;
}
};
  • 33 Search in Rotated Sorted Array
/*
* @lc aleetcode刷题攻略pp=appreciateleetcode id=33 lang=cpp
*
* [33] Search in Rotated Sorted Array
*/
// @lc code=start
#elementanimationinclude <leetcode刷题攻略bits/stdc++.h>
using namespacleetcode是什么e std;
class Solution {
public:
int search(vector<int>& nums, int target) {
if(nums.emleetcode中文官网pty())
retappearurn -1;
int l = 0, r = numapples.size() - 1;
whielementary怎么读英语le (l < r)
{
int mid = (l + r) /2;
if (nums[mid] >= target && ((nLeetCodeums[leetcode刷题网站mid] <= nums[r] )||(telementuiarget >=leetcode每日一题 nums[l])))
{
r = mid;
}
else if (nums[mid] < target && target &gtleetcode刷题网站;= nums[l] && nums[mid] < numleetcode题库s[l])
{
r = mid - 1;
}else{
l = mid+1;
}
}
return nums[l] == target ? l : -1;
}
};
// @lc code=end

发表评论

提供最优质的资源集合

立即查看 了解详情