comments | difficulty | edit_url | tags | ||
---|---|---|---|---|---|
true |
简单 |
|
给你一个正整数 num
。如果 num
是一个完全平方数,则返回 true
,否则返回 false
。
完全平方数 是一个可以写成某个整数的平方的整数。换句话说,它可以写成某个整数和自身的乘积。
不能使用任何内置的库函数,如 sqrt
。
示例 1:
输入:num = 16 输出:true 解释:返回 true ,因为 4 * 4 = 16 且 4 是一个整数。
示例 2:
输入:num = 14 输出:false 解释:返回 false ,因为 3.742 * 3.742 = 14 但 3.742 不是一个整数。
提示:
1 <= num <= 231 - 1
我们可以使用二分查找来解决这个问题。定义二分查找的左边界
时间复杂度
class Solution:
def isPerfectSquare(self, num: int) -> bool:
l = bisect_left(range(1, num + 1), num, key=lambda x: x * x) + 1
return l * l == num
class Solution {
public boolean isPerfectSquare(int num) {
int l = 1, r = num;
while (l < r) {
int mid = (l + r) >>> 1;
if (1L * mid * mid >= num) {
r = mid;
} else {
l = mid + 1;
}
}
return l * l == num;
}
}
class Solution {
public:
bool isPerfectSquare(int num) {
int l = 1, r = num;
while (l < r) {
int mid = l + (r - l) / 2;
if (1LL * mid * mid >= num) {
r = mid;
} else {
l = mid + 1;
}
}
return 1LL * l * l == num;
}
};
func isPerfectSquare(num int) bool {
l := sort.Search(num, func(i int) bool { return i*i >= num })
return l*l == num
}
function isPerfectSquare(num: number): boolean {
let [l, r] = [1, num];
while (l < r) {
const mid = (l + r) >> 1;
if (mid >= num / mid) {
r = mid;
} else {
l = mid + 1;
}
}
return l * l === num;
}
impl Solution {
pub fn is_perfect_square(num: i32) -> bool {
let mut l = 1;
let mut r = num as i64;
while l < r {
let mid = (l + r) / 2;
if mid * mid >= (num as i64) {
r = mid;
} else {
l = mid + 1;
}
}
l * l == (num as i64)
}
}
由于
时间复杂度
class Solution:
def isPerfectSquare(self, num: int) -> bool:
i = 1
while num > 0:
num -= i
i += 2
return num == 0
class Solution {
public boolean isPerfectSquare(int num) {
for (int i = 1; num > 0; i += 2) {
num -= i;
}
return num == 0;
}
}
class Solution {
public:
bool isPerfectSquare(int num) {
for (int i = 1; num > 0; i += 2) {
num -= i;
}
return num == 0;
}
};
func isPerfectSquare(num int) bool {
for i := 1; num > 0; i += 2 {
num -= i
}
return num == 0
}
function isPerfectSquare(num: number): boolean {
let i = 1;
while (num > 0) {
num -= i;
i += 2;
}
return num === 0;
}
impl Solution {
pub fn is_perfect_square(mut num: i32) -> bool {
let mut i = 1;
while num > 0 {
num -= i;
i += 2;
}
num == 0
}
}