367. Valid Perfect Square

Easy
O(n)的方法

class Solution {
    public boolean isPerfectSquare(int num) {
        if (num <= 0){
            return false;
        }   
        if (num == 1){
            return true;
        }
        for(long i = 1; i*i <= num; i++){
            if (i * i == num){
                return true;
            }
        }
        return false;
    }
}

O(logn)的方法用的是Binary Search, 用的自己最熟的模版,注意越界所以用long.

class Solution {
    public boolean isPerfectSquare(int num) {
        if (num <= 0){
            return false;
        }   
        if (num == 1){
            return true;
        }
        long start = 1;
        long end = num;
        while (start + 1 < end){
            long mid = start + (end - start) / 2;
            long square = mid * mid;
            if (square < num){
                start = mid;    
            } else if (square > num){
                end = mid;
            } else {
                return true;
            }
        }
        return false;
    }
}

你可能感兴趣的:(367. Valid Perfect Square)