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

    14First Position of Target

    二分查找的基础题

    STL lower_bound实现

    class Solution {
    public:
        /**
         * @param nums: The integer array.
         * @param target: Target to find.
         * @return: The first position of target. Position starts from 0.
         */
        int binarySearch(vector<int> &nums, int target) {
            // write your code here
            
            auto res_it=lower_bound(nums.begin(),nums.end(),target);
            auto it=nums.begin();
            int i=0;
            if(*res_it != target)return -1;
            return &(*res_it)-&(nums[0]);
            
        }
    };
    

    迭代器和下标可使用 取地址符 进行转换 (原理是vector变量在内存上连续分布)

    传统算法实现

    class Solution {
    public:
        /**
         * @param nums: The integer array.
         * @param target: Target to find.
         * @return: The first position of target. Position starts from 0.
         */
        int binarySearch(vector<int> &nums, int target) {
            // write your code here
            
            int left = -1;
            int right = nums.size();
            
            while(right - left > 1)
            {
                int mid = (left+right)/2;
                if(target<=nums[mid])
                {
                    right = mid;
                }else{
                    left = mid;
                }
                
            }
            if(nums[right] != target)return -1;
            return right;
    
        }
    };
    

    需要注意的是

    • 区间为左开 (其原因是 整型变量 (2+3)/2=3 )
    • 当搜索到=号的时候,拉右边到中间(right = mid)
  • 相关阅读:
    一元多项式乘法
    将博客搬至CSDN
    Tomcat的几种部署方式
    Visual Studio 2012以后无法保存只读文件的问题
    WPF中的Generic.xaml, theme以及custom control
    WPF的页面导航
    WPF MVVM系列文章
    tomcat中同时部署两个项目的问题
    Windows多线程系列
    XML DTD和XML Schema
  • 原文地址:https://www.cnblogs.com/virgildevil/p/11824267.html
Copyright © 2011-2022 走看看