zoukankan      html  css  js  c++  java
  • LeetCode

    34. Search for a Range 

    Problem's Link

     ----------------------------------------------------------------------------

    Mean: 

    给定一个有序数组和一个数k,求k在这个数组中的起始下标和结束下标.

    analyse:

    二分查找.

    Time complexity: O(N)

     

    view code

    /**
    * -----------------------------------------------------------------
    * Copyright (c) 2016 crazyacking.All rights reserved.
    * -----------------------------------------------------------------
    *       Author: crazyacking
    *       Date  : 2016-03-01-22.03
    */
    #include <queue>
    #include <cstdio>
    #include <set>
    #include <string>
    #include <stack>
    #include <cmath>
    #include <climits>
    #include <map>
    #include <cstdlib>
    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <cstring>
    using namespace std;
    typedef long long(LL);
    typedef unsigned long long(ULL);
    const double eps(1e-8);

    class Solution
    {
    public:
       vector<int> searchRange(vector<int>& nums, int target)
       {
           vector<int> ret;
           int len=nums.size();
           int low=0,high=len-1;
           while(low<=high)
           {
               int mid=(low+high)>>1;
               if(target<nums[mid])
                   high=mid-1;
               else if(target>nums[mid])
                   low=mid+1;
               else
               {
                   int frontIndex=mid,backIndex=mid;
                   while(frontIndex-1>=0 && nums[frontIndex]==nums[frontIndex-1])
                       --frontIndex;
                   while(backIndex+1<len && nums[backIndex]==nums[backIndex+1])
                       ++backIndex;
                   ret.push_back(frontIndex);
                   ret.push_back(backIndex);
                   return ret;
               }
           }
           ret.push_back(-1);
           ret.push_back(-1);
           return ret;
       }
    };

    int main()
    {
       Solution solution;
       int n,k;
       while(cin>>n>>k)
       {
           vector<int> ve;
           for(int i=0;i<n;++i)
           {
               int tempVal;
               cin>>tempVal;
               ve.push_back(tempVal);
           }
           ve=solution.searchRange(ve,k);
           for(auto p:ve)
               cout<<p<<endl;
       }
       return 0;
    }
    /*

    */
  • 相关阅读:
    路由器配置深入浅出—静态路由和缺省路由配置
    盘点飞思卡尔i.MX多媒体处理器前世今生 (转)
    ubuntu18.04下取消中键复制粘贴功能
    uboot常用命令及其使用
    MCU软件最佳实践——使用printf打印数据
    uboot无法通过nfs加载ubuntu18.04中的文件(转)
    GNU C字节对齐__attribute__((aligned(n))) #pragma pack(n)
    ENDIAN的由来及BIGEDIAN 和LITTLEENDIAN(转)
    自动生成c# Model属性
    使用JAVA生成随机的AES密钥
  • 原文地址:https://www.cnblogs.com/crazyacking/p/5232761.html
Copyright © 2011-2022 走看看