367. Valid Perfect Square

Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt.
Example 1:

Input: 16
Returns: True

Example 2:

Input: 14
Returns: False

Solution1:Math

思路:A square number is 1+3+5+7+...
Time Complexity: O(sqrt(n)) Space Complexity: O(1)

Solution2:Binary Search

Time Complexity: O(log(n)) Space Complexity: O(1)

Solution3:Newton Methold

reference: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
Time Complexity: O(log(n)) Space Complexity: O(1)

Solution1 Code:

class Solution1 {
    public boolean isPerfectSquare(int num) {
        int i = 1;
        while (num > 0) {
            num -= i;
            i += 2;
        }
        return num == 0;
    }
}

Solution2 Code:

class Solution {
    public boolean isPerfectSquare(int num) {
        int start = 1, end = num;
        while(start <= end) {
            int mid = start + (end - start) / 2;
            if (num / mid == mid && num % mid == 0) { //becuase mid * mid will overflow
                return true;
            } else if (num / mid > mid) {
                start = mid + 1;
            } else {
                end = mid - 1;
            }
        }
        return false;
    }
}

Solution3 Code:

class Solution {
    public boolean isPerfectSquare(int num) {
        long x = num;
        while (x * x > num) {
            x = (x + num / x) >> 1;
        }
        return x * x == num;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容