zoukankan      html  css  js  c++  java
  • 二分查找 变形

    #include<iostream>
    using namespace std;
    
    int helper(int a[],int len,int t,bool isleft)
    {
        if(a == NULL || 0 >= t) return EOF;
    
        int last = EOF;
        int left = 0;
        int right = len - 1;
    
        while(left <= right)
        {
            int middle = (left + right)/2;
            if(a[middle] > t)
            {
              right = middle - 1;
            }
            else if(a[middle]<t)
            {
              left = middle + 1;
            }else{
              last = middle;
              if(isleft)
                  right = middle-1;
              else
                  left = middle + 1;
            }
        }
        return last;
    }
    
    int main()
    {
        int a[] = {1,1,2,2,2,2,3,4,5};
        int left = helper(a,sizeof(a)/sizeof(a[0]),2,true);
        int right = helper(a,sizeof(a)/sizeof(a[0]),2,false);
        if(EOF != left && EOF != right)
            cout<<left<<" "<<right<<" "<<right-left + 1<<endl;
        else
            cout<<left<<" "<<right<<" "<<"can not found"<<endl;
    
    }
    #include<stdio.h>
    
    int solver(const int a[],const int n,const int t)
    {
      int total = 0;
      if (NULL == a && 0 >= n)
          return total;
      int start = 0;
      int end = n-1;
      while(start <= end)
      {
       printf("%d   %d
    ",start,end);
       int middle = (start + end)/2;
       if(t == a[middle])
       {
         total = 1;
         int cursor = 0;
         while(++cursor && middle + cursor < n && t == a[middle + cursor])
           total++;
         cursor = 0;
         while(--cursor && middle + cursor >= 0 && t == a[middle + cursor])
            total++;
         return total;
       }
       else if(t > a[middle])
        end = middle - 1;
       else
        start = middle + 1;
      }
      return total;
    }
    
    int main()
    {
        int a[] = {1,1,1,1,1,1};
        int b[] = {1,2,2,2,2,3};
        int c[] = {1,2,3,5,6,7};
        printf("%d",solver(b,6,4));
    }
    berkeleysong
  • 相关阅读:
    luogu 3388 【模板】割点(割顶)
    bzoj 3624 免费道路
    bzoj 1179 Atm
    bzoj 2428 均分数据
    luogu 4429 染色
    luogu 4427 求和
    luogu 1121 环状最大两段子段和
    hdu 4777 Queue
    hdu 5492 Find a path
    hdu 5441 Travel
  • 原文地址:https://www.cnblogs.com/berkeleysong/p/3733954.html
Copyright © 2011-2022 走看看