leetcode (Valid Perfect Square)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/85332745

Title:Ugly Number    367

Difficulty:Easy

原题leetcode地址:   https://leetcode.com/problems/valid-perfect-square/

1.   从1开始判断乘积是否等于num,但是结束的判断时(num / i)

时间复杂度:O(n),一次一层for循环,循环最长为n。

空间复杂度:O(1),没有申请额外空间。

    /**
     * 从1开始判断乘积是否等于num,但是结束的判断时(num / i)
     * @param num
     * @return
     */
    public static boolean isPerfectSquare(int num) {

        if (num < 1) {
            return false;
        }

        for (int i = 1; i <= num / i; i++) {
            if (i * i == num) {
                return true;
            }
        }

        return false;

    }

2.  二分法

时间复杂度:O(logn),一次一层while循环。

空间复杂度:O(1),没有申请额外空间。

    /**
     * 二分法
     * @param num
     * @return
     */
    public static boolean isPerfectSquare2(int num) {

        if (num < 1) {
            return false;
        }

        if (num == 1) {
            return true;
        }

        int start = 1;
        int end = num / 2;

        while (start <= end) {
            int mid = (start + end) / 2 + 1;
            if (mid * mid == num) {
                return true;
            }
            if (mid * mid < num) {
                start = mid + 1;
            }
            if (mid * mid > num) {
                end = mid - 1;
            }
        }

        return false;

    }

3.  推理法

时间复杂度:O(n),一次一层while循环。

空间复杂度:O(1),没有申请额外空间。

    /**
     * n^2 = 1 + 3 + 5 + 7
     * @param num
     * @return
     */
    public static boolean isPerfectSquare3(int num) {

        if (num < 1) {
            return false;
        }

        int i = 1;

        while (num > 0) {
            num -= i;
            i += 2;
        }

        return num == 0;

    }

3.  Math法

时间复杂度:O(1),没有循环、递归。

空间复杂度:O(1),没有申请额外空间。

    /**
     * Math函数
     * @param num
     * @return
     */
    public static boolean isPerfectSquare4(int num) {

        if (num < 1) {
            return false;
        }

        double n = Math.sqrt(num);
        
        return (n - Math.floor(n) == 0);

    }

猜你喜欢

转载自blog.csdn.net/hsx1612727380/article/details/85332745
今日推荐