valid-perfect-square
Problem
Problem Description
Solution
This problem can use binary search from [1, N/2], all other numbers (num) square is less than num / 2. expect 1 and 2, for 1 do additional check.
if N == 1, return true.
define lo = 1; hi = N / 2;
check mid = lo + (hi - lo) / 2; -- to avoid overflow
check mid * mid compare with current N;
if mid * mid == N, found, return mid and terminate
if mid * mid < N, meaning possible number is in right half, reset lo = mid + 1. continue check right half [mid + 1, hi]
if mid * mid > N, meaning possible number is in left hald, reset hi = mid - 1. continue check left half [lo, mid - 1]
until lo == hi, if not found, return false
Note: using long type for lo and hi, and mid, because mid * mid may be overflow.
For example:
Complexity Analysis
Time Complexity: O(logN)
Space Complexity: O(1)
N - input number N
Code
Last updated