時間復雜度為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; }