LeetCode 367 有效的完全平方數

2022-09-22 06:11:39 字數 2657 閱讀 3576

問題描述:

給定一個正整數 num,編寫一個函式,如果 num 是一個完全平方數,則返回 true,否則返回 false。

說明:不要使用任何內建的庫函式,如sqrt

示例 1:

輸入:16輸出:true
示例 2:

輸入:14輸出:false
官方:

1

class

solution(object):

2def

isperfectsquare(self, num):

3"""

4:type num: int

5:rtype: bool

6"""

7 left, right = 1, num

8while left <=right:

9 mid = left + (right - left) / 2

10if mid >= num /mid:

11 right = mid - 1

12else

:13 left = mid + 1

14return left == num / left and num % left == 0

官方2:

1

class

solution(object):

2def

isperfectsquare(self, num):

3"""

4:type num: int

5:rtype: bool

6"""

7 self.num=num

8if num==1:

9return

true

10 low=1

11 high=num

12while high-low>1:

13 mid=int((high+low)/2)

14if mid**2==num:

15return

true

16if mid**2>num:

17 high=mid

18if mid**219 low=mid

20return false

違反規定:

1

import

math

2class

solution(object):

3def

isperfectsquare(self, num):

4"""

5:type num: int

6:rtype: bool

7""" #4.0

8 a = str(math.sqrt(num)).split("

.")[1]

9if a !='0'

:10return

false

11return true

另外:

1

import

math

2class

solution(object):

3def

isperfectsquare(self, num):

4"""

5:type num: int

6:rtype: bool

7"""

8if num <0:

9return

false

10 i =0

11while i**2 12 i += 1

13return i**2 == num

最後為什麼時間超限:

1

class

solution(object):

2def

isperfectsquare(self, num):

3"""

4:type num: int

5:rtype: bool

6"""

7 left = 1

8 right =num

9while

left <=

num: # <= right

10 mid = (left + right) // 2

11if mid**2 ==num:

12return

true

13if mid**2 14 left =mid + 1

15if mid**2 >num:

16 right =mid -1

17return false

2018-09-27 10:08:09