Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 67d78a8

Browse files
committed
Update binary_search.md
lc367 有效完全平方数
1 parent b1927a7 commit 67d78a8

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

‎basic_algorithm/binary_search.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,29 @@ class Solution:
112112
113113
```
114114

115+
### [有效的完全平方数](https://leetcode.cn/problems/valid-perfect-square/)
116+
> 给定一个 正整数 num ,编写一个函数,如果 num 是一个完全平方数,则返回 true ,否则返回 false 。
117+
> 进阶:不要 使用任何内置的库函数,如 sqrt 。
118+
119+
思路:只要`num`大于4,其平方数肯定不会超过`num//2`,这样可以减少一次二分运算,提升速度.
120+
121+
**Python版本**
122+
```python
123+
class Solution:
124+
def isPerfectSquare(self, num: int) -> bool:
125+
left, right = 1, num // 2 + 1
126+
while left + 1 < right:
127+
mid = left + (right - left) // 2
128+
if mid * mid == num: return True
129+
elif mid * mid < num: left = mid
130+
else:
131+
right = mid
132+
if left * left == num or right * right == num: return True
133+
else: return False
134+
```
135+
136+
137+
115138
### [猜数字大小](https://leetcode.cn/problems/guess-number-higher-or-lower/)
116139
> 猜数字游戏的规则如下:
117140
> 每轮游戏,我都会从 1 到 n 随机选择一个数字。 请你猜选出的是哪个数字。

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /