1.求开方
class Solution {
public:
bool guess(long x, long y){
return x*x<=y;
}
public:
int mySqrt(int y) {
long L=0,R=(long)y+1;//区间
long ans=0;
while(L<R){
long mid=(L+R)/2;
if (guess(mid,y)){
ans=mid;
L=mid+1;
}else
R=mid;
}
return ans;
}
};
2.最大分割数组
class Solution {
public boolean guess(long mid,int[] nums,int m){
long sum=0;
long mm=0;
for(int i=0;i<nums.length;++i){
if(sum+nums[i]>mid){
++mm;
sum=nums[i];
if(nums[i]>mid)
{return false;}
}else
{sum+=nums[i];}
}
return mm<m;
}
public int splitArray(int[] nums, int m) {
int n=nums.length;
long R=1;
for(int i=0;i<n;i++){
R+=nums[i];
}
long L=0;
long ans=0;
while(L<R){
long mid=(L+R)/2;
if (guess(mid,nums,m)){
ans=mid;
//L=mid+1;
R=mid;
}else
L=mid+1;
}
return (int)ans;
}
};
3.倍增法求幂
class Solution {
public double myPow(double x, int n) {
if(n==0)
{return 1;}
double A=myPow(x,n/2);
if(n%2==0){
return A*A;
}else{
double A=myPow(x,n/2);
return A*A*x;
}
}
}