• 如何在 1000 万个整数中快速查找某个整数?——二分查找


    • 时间复杂度O(logn),很强
    • 适用于数组的数据结构,但不适用于链表,因为链表不支持随机访问
    • 只能查找有序数组,如果是无序的,需要进行一次排序(最低时间复杂度O(nlogn))
    • 数据量小不适用,直接用遍历查找即可
    • 数据量太大也不适用,因为数据结构是数组,需要的是连续的内存空间
    #include <iostream>
    #include <vector>
    #include <stack>
    #include <cstring>
    #include <string>
    #include <queue>
    #include <algorithm>
    #include "TreeNode.h"
    #include "ListNode.h"
    using namespace std;
    
    // 二分查找具有O(logn)的时间复杂度,很强,但是只能用于数组的数据结构,像链表就不适合
    
    // 二分查找非递归法
    int binarySearch(int num[], int length, int key){
        if(length < 1)
            return -1;
        int low = 0;
        int high = length - 1;
        int middle = 0;
        while(low <= high){
            // 以后尽量使用位运算,不直接用(low + high) / 2是为了防止加法溢出
            middle = low + ((high - low) >> 1);
            if(num[middle] == key)
                return middle;
            if(num[middle] > key)
                high = middle - 1;
            else if(num[middle] < key)
                low = middle + 1;
        }
        // 没找到则返回-1
        return -1;
    }
    
    // 二分查找递归方法
    int binarySearchPlus(int num[], int low, int high, int key){
        if(low > high)
            return -1;
        int middle = low + ((high - low) >> 1);
        if(num[middle] == key)
            return middle;
        if(num[middle] > key)
            return binarySearchPlus(num, low, middle - 1, key);
        else
            return binarySearchPlus(num, middle + 1, high, key);
    }
    
    int main(int argc, char* argv[]){
    
        int arr[8] = {8,7,6,5,4,3,2,1};
        cout<<binarySearch(arr, 8, 5)<<endl;
        cout<<binarySearchPlus(arr, 0, 7, 5)<<endl;
    
        return 0;
    }
    
  • 相关阅读:
    刷新验证码
    网页的超链接传递中文参数乱码问题
    Button获取Repeater一行的两个值
    <asp:FileUpload>上传一张图片并且重命名
    <asp:DropDownList数据库读取
    <asp:DropDownList>用法
    <%#Eval(" ")%>用法总结
    DropDownList1 .cs指定初始值
    redolog(未完工)
    cap理论
  • 原文地址:https://www.cnblogs.com/flyingrun/p/13423302.html
Copyright © 2020-2023  润新知