ProblemSet of Binary Search Algorithms

二分的模板:真的很好用,谁用谁知道

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

LeetCode

852. Peak Index in a Mountain Array

class Solution {
    public int peakIndexInMountainArray(int[] nums) {
        
        int l=0,r=nums.length-1;
        while(l>1;
            if(isDecline(mid,nums))
            {
                r=mid;
            }
            else{
                l=mid+1;
            }
        }
        return l;
    }
    
    
    public static boolean isDecline(int i,int[] nums){
        if(nums[i]>nums[i+1])
            return true;
        else
            return false;
    }
}

AcWing

102. 最佳牛围栏

#include
#include
using namespace std;
const int N=100005;
int arr[N];
double preSum[N];
int n,F;

bool check(double mid){
    
    for(int i=1;i<=n;i++)
    {
        preSum[i]=preSum[i-1]+arr[i]-mid;
    }
    double minv=0;
    for(int j=F,i=0;j<=n;j++,i++)
    {
        minv=min(minv,preSum[i]);
        if(preSum[j]-minv>=0)
            return true;
    }
    return false;
}

int main(){
    

    cin>>n>>F;
    for(int i=1;i<=n;i++)
        cin>>arr[i];
    double l=1,r=2000;
    while(r-l>1e-5)
    {
        double mid=(l+r)/2;
        if(check(mid))
            l=mid;
        else
            r=mid;
    }
    cout<<(int)(r*1000)<

113. 特殊排序
算法一:归并排序

class Solution {
public:

    vector merge(int i,int j,int N){
        if(i==j)
        {
            vector tmp;
            tmp.push_back(i);
            return tmp;
        }
        
        int mid=(i+j)/2;
        //cout< ans1=merge(i,mid,N);
        vector ans2=merge(mid+1,j,N);
        
        vector ans;
        int i1=0;
        int i2=0;
        while(i1 specialSort(int N) {
        vector ans=merge(1,N,N);
        return ans;
    }
};

算法二:
二分法:这个二分有点玄学

// Forward declaration of compare API.
// bool compare(int a, int b);
// return bool means whether a is less than b.

class Solution {
public:
    vector specialSort(int N) {
        vector ans;
        ans.push_back(1);
        for(int i=2;i<=N;i++){
            
            int l=0,r=ans.size()-1;
            //二分找到最后一个比i小的位置
            while(ll;j--){
                swap(ans[j+1],ans[j]);
            }
            if(compare(i,ans[l]))
                swap(ans[l+1],ans[l]);
            
        }
        return ans;
    }
};

你可能感兴趣的:(ProblemSet of Binary Search Algorithms)