367. Valid Perfect Square(python+cpp)(c++代码超时

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

题目:

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 
Output: true 

Example 2:

Input: 14 
Output: false

解释:
判断一个数是不是平方数。注意不能用自带的开根号函数。
完全平方数有一个数学规律,它是一系列连续的奇数的求和:
1 = 1
4 = 1 + 3
9 = 1 + 3 + 5
16 = 1 + 3 + 5 + 7
25 = 1 + 3 + 5 + 7 + 9
36 = 1 + 3 + 5 + 7 + 9 + 11

1+3+…+(2n-1) = (2n-1 + 1)n/2 = n*n

二分查找解法,python代码:

class Solution(object):
    def isPerfectSquare(self, num):
        """
        :type num: int
        :rtype: bool
        """
        low=0
        high=num
        while low<=high:
            mid=(low+high)/2
            temp=mid*mid
            if temp==num:
                return True
            elif temp>num:
                high=mid-1
            else:
                low=mid+1
        return False      

c++代码,居然超时??

class Solution {
public:
    bool isPerfectSquare(int num) {
        int left=0,right=num;
        while(left<=right)
        {
            int mid=left+(right-left)/2;
            int tmp=mid*mid;
            if(tmp==num)
                return true;
            else if(tmp<num)
                left=mid+1;
            else
                right=mid-1;
        }
        return false;
    }
};

数学解法python代码:

class Solution(object):
    def isPerfectSquare(self, num):
        """
        :type num: int
        :rtype: bool
        """
        i=1
        while num>0:
            num-=i
            i+=2
        return num==0

c++代码:

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

总结:
注意二分查找方法的时候是<=
为什么二分查找的c++代码超时了??

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/83573413