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)
  • 相关阅读:
    Linux system basic 2 + add kernel for Jupyter
    Linux package installation: deb and rpm
    classification tips 01: npy file
    how to activate XMind8 to pro version.
    Linux system 初步
    try_except_finally
    Postgresql Json Sql
    python package install error and little code bugs
    小程序用户操作事件
    套数据操作步骤
  • 原文地址:https://www.cnblogs.com/virgildevil/p/11824267.html
Copyright © 2011-2022 走看看