二分法的精髓:函数的单调性 + 计算内容重复 (注意:不同于分治)
根据区间范围,猜测答案的结果。
1. Sqrt(x)求平方根
public int mySqrt(int y)
{
int left = 0;
int right = y;
long mid = 0;
// 区间范围[0, y]
while (left <= right)
{
mid = (left + right) / 2;
System.out.println(mid);
long res = mid * mid;
if (res < y)
{
left = (int) (mid + 1);
}
else if (res == y)
{
return (int) mid;
}
else
{
right = (int) (mid - 1);
}
}
return right;
}
public boolean guess(long x, long y)
{
return (x*x) <=y ? true:false;
}
public int mySqrt(int y)
{
long left = 0;
long right = (long)y+1;
long ans = 0;
// 区间范围[0, y+1)
while (left < right)
{
long mid = (left + right) / 2;
if (guess(mid, y)==true)
{
ans = mid;
left = mid + 1;
}
else
{
right = (int) mid;
}
}
return (int)ans;
}
2. Split Array Largest Sum
https://blog.csdn.net/tc_1337/article/details/81591277