二分法解題思路

-Billy發表於2018-08-11

二分法的精髓:函式的單調性 +  計算內容重複 (注意:不同於分治)

根據區間範圍,猜測答案的結果。

 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

 

相關文章