時間復雜度為O(logN)的常用算法


時間復雜度為O(logN)的常用算法

折半查找

/*
     * 折半查找
     * 默認查找的數組已經排過序
     */
    public static int binarySearch(int[] a,int x){
        int low=0,high=a.length-1;
        while(low<=high){
            int mid =(low+high)/2;
            if(a[mid]<x){
                low=mid+1;
            }else if(a[mid]>x){
                high=mid-1;
            }else{
                return mid;
            }
        }
        return -1;
    }

歐幾里得算法

/*
     * 歐幾里得算法求最大公因數
     * 默認m>n
     */
    public static int gcd(int m,int n){
        while(n!=0){
            int rem=m%n;
            m=n;
            n=rem;
        }
        return m;
    }

冪運算

/*
     * 冪運算
     */
    public static int pow(int x,int n){
        if(n==0)
            return 1;
        if(n==1)
            return x;
        if(n%2==0)
            return pow(x*x,n/2);
        else
            return pow(x*x,n/2)*x;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM