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
Returns: True

Example 2:

Input: 14
Returns: False

Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.

这道题给了我们一个数,让我们判断其是否为完全平方数,那么显而易见的是,肯定不能使用 brute force,这样太不高效了,那么最小是能以指数的速度来缩小范围,那么我最先想出的方法是这样的,比如一个数字 49,我们先对其除以2,得到 24,发现 24 的平方大于 49,那么再对 24 除以2,得到 12,发现 12 的平方还是大于 49,再对 12 除以2,得到6,发现6的平方小于 49,于是遍历6到 12 中的所有数,看有没有平方等于 49 的,有就返回 true,没有就返回 false,参见代码如下:

解法一:

class Solution {
public:
bool isPerfectSquare(int num) {
if (num == ) return true;
long x = num / , t = x * x;
while (t > num) {
x /= ;
t = x * x;
}
for (int i = x; i <= * x; ++i) {
if (i * i == num) return true;
}
return false;
}
};

下面这种方法也比较高效,从1搜索到 sqrt(num),看有没有平方正好等于 num 的数:

解法二:

class Solution {
public:
bool isPerfectSquare(int num) {
for (int i = ; i <= num / i; ++i) {
if (i * i == num) return true;
}
return false;
}
};

我们也可以使用二分查找法来做,要查找的数为 mid*mid,参见代码如下:

解法三:

class Solution {
public:
bool isPerfectSquare(int num) {
long left = , right = num;
while (left <= right) {
long mid = left + (right - left) / , t = mid * mid;
if (t == num) return true;
if (t < num) left = mid + ;
else right = mid - ;
}
return 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

这里就不做证明了,我也不会证明,知道了这条性质,就可以利用其来解题了,时间复杂度为 O(sqrt(n))。

解法四:

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

下面这种方法是第一种方法的类似方法,更加精简了,时间复杂度为 O(lgn):

解法五:

class Solution {
public:
bool isPerfectSquare(int num) {
long x = num;
while (x * x > num) {
x = (x + num / x) / ;
}
return x * x == num;
}
};

这道题其实还有 O(1) 的解法,这你敢信?简直太丧心病狂了,详情请参见论坛上的这个帖子

Github 同步地址:

https://github.com/grandyang/leetcode/issues/367

类似题目:

Sqrt(x)

参考资料:

https://leetcode.com/problems/valid-perfect-square/

https://leetcode.com/problems/valid-perfect-square/discuss/83872/O(1)-time-c%2B%2B-solution-inspired-by-Q_rsqrt

https://leetcode.com/problems/valid-perfect-square/discuss/83874/A-square-number-is-1%2B3%2B5%2B7%2B...-JAVA-code

https://leetcode.com/problems/valid-perfect-square/discuss/83902/Java-Three-Solutions-135..-SequenceBinary-SearchNewton

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Valid Perfect Square 检验完全平方数的更多相关文章

  1. [LeetCode] 367. Valid Perfect Square 检验完全平方数

    Given a positive integer num, write a function which returns True if num is a perfect square else Fa ...

  2. [leetcode]367. Valid Perfect Square验证完全平方数

    Given a positive integer num, write a function which returns True if num is a perfect square else Fa ...

  3. [LeetCode]367. Valid Perfect Square判断完全平方数

    方法有很多,我觉得比较容易记住的是两个,一个是二分法,在1-num/2中寻找目标数 另一个是数学方法: public boolean isPerfectSquare(int num) { /* 有很多 ...

  4. LeetCode "Valid Perfect Square"

    Typical binary search.. but take care of data overflow if you are using C++ class Solution { public: ...

  5. Leetcode之二分法专题-367. 有效的完全平方数(Valid Perfect Square)

    Leetcode之二分法专题-367. 有效的完全平方数(Valid Perfect Square) 给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 ...

  6. 367. Valid Perfect Square

    原题: 367. Valid Perfect Square 读题: 求一个整数是否为完全平方数,如1,4,9,16,……就是完全平方数,这题主要是运算效率问题 求解方法1:812ms class So ...

  7. LeetCode_367. Valid Perfect Square

    367. Valid Perfect Square Easy Given a positive integer num, write a function which returns True if  ...

  8. C#LeetCode刷题之#367-有效的完全平方数(Valid Perfect Square)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3869 访问. 给定一个正整数 num,编写一个函数,如果 num ...

  9. [Swift]LeetCode367. 有效的完全平方数 | Valid Perfect Square

    Given a positive integer num, write a function which returns True if num is a perfect square else Fa ...

随机推荐

  1. 利用Python进行数据分析(14) pandas基础: 数据转换

    数据转换指的是对数据的过滤.清理以及其他的转换操作. 移除重复数据 DataFrame里经常会出现重复行,DataFrame提供一个duplicated()方法检测各行是否重复,另一个drop_dup ...

  2. php的laravel框架快速集成微信登录

    最终的解决方案是:https://github.com/liuyunzhuge/php_weixin_provider,详细的介绍请往下阅读. 本文面向的是php语言laravel框架的用户,介绍的是 ...

  3. NopCommerce 在Category 显示Vendor List列表

    实现效果如下: 1.在前台Web的Category Menu显示 Vendor; 2.点击Vendor 显示Vendor List列表: 主要配置步骤: 1.运行网站 Admin 后台   Categ ...

  4. WPF绑定到集合

    什么是集合视图? 集合视图是位于绑定源集合顶部的一层,您可以通过它使用排序.筛选和分组查询来导航和显示源集合,而无需更改基础源集合本身.集合视图还维护着一个指向集合中的当前项的指针.如果源集合实现了 ...

  5. [python] CSV read and write using module xlrd and xlwt

    1. get data from csv, skip header of the file. with open('test_data.csv','rb,) as csvfile: readCSV = ...

  6. php的面向对象

    今天PO一段php的面向对象相关知识吧.面向对象的相关概念和理论知识是很抽象的,要结合现实中的事物来理解,这样有助于类比记忆.还有就是要多接触吧,量变引质变这个应该还是一个硬道理吧,有时候量够了的话, ...

  7. 利用H5和ChromiumWebBrowser构建应用

    chromium是google chrome浏览器所采用的内核,最开始由苹果的webkit发展而出,由于webkit在发展上存在分歧,而google希望在开发上有更大的自由度,2013年google决 ...

  8. js实现toggleClass

  9. CSS选择器的权重与优先规则?

    我们做项目的时候,经常遇到样式层叠问题,被其他的样式覆盖,或者写的权重不高没效果,对权重没有具体的分析,做了一个总结. css继承是从一个元素向其后代元素传递属性值所采用的机制.确定应当向一个元素应用 ...

  10. iOS报错[__NSCFNumber length]: unrecognized

    出现这种报错很大的原因是因为类型给错了,或许你这个数据是从json上解析后得到的,但是需要看一下这个数据是NSString还是NSNumber类型,如果是NSNumber类型的话,你又直接使用NSSt ...