367. Valid Perfect Square(python+cpp)(c++程式碼超時
阿新 • • 發佈:2018-11-03
題目:
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++程式碼超時了??