zoukankan      html  css  js  c++  java
  • LeetCode

    35. Search Insert Position 

    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-02-08.49
    */
    #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:
       int searchInsert(vector<int>& nums, int target)
       {
           int len=nums.size();
           if(len==0 || target<=nums[0])
               return 0;
           if(target>nums[len-1])
               return len;
           int low=0,high=len-1;
           while(low<=high)
           {
               int mid=(low+high)>>1;
               if(target<nums[mid])
               {
                   if(mid-1>=0 && target>nums[mid-1])
                       return mid;
                   high=mid-1;
               }
               else if(target>nums[mid])
               {
                   if(mid+1<len && target<nums[mid+1])
                       return mid+1;
                   low=mid+1;
               }
               else
                   return mid;
           }
       }
    };

    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);
           }
           cout<<"pos="<<solution.searchInsert(ve,k)<<endl;
       }
       return 0;
    }
    /*

    */
  • 相关阅读:
    亚马逊云服务器VPS Amazon EC2 免费VPS主机配置CentOS及其它内容
    Linux + Mono 目前已经支持Entity Framework 6.1
    CentOS上 Mono 3.2.8运行ASP.NET MVC4经验
    Linux CentOS下如何确认MySQL服务已经启动
    C#使用Timer.Interval指定时间间隔与指定时间执行事件
    MySQL数据库有外键约束时使用truncate命令的办法
    C++中字符和字符串的读取与使用
    结构体的运算符重载
    P1358 扑克牌
    P1284 三角形牧场
  • 原文地址:https://www.cnblogs.com/crazyacking/p/5233587.html
Copyright © 2011-2022 走看看