首页 > 其他 > 详细

Leetcode: Valid Perfect Squares

时间:2016-11-24 14:22:20      阅读:171      评论:0      收藏:0      [点我收藏+]
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

我的binary Search 解法:无需变成long

 1 public class Solution {
 2     public boolean isPerfectSquare(int num) {
 3         if (num <= 0) return false;
 4         int l=1, r=num/2+1;
 5         while (l <= r) {
 6             int mid = l + (r-l)/2;
 7             if (mid == num/mid && num%mid == 0) return true;
 8             else if (mid > num/mid) {
 9                 r = mid - 1;
10             }
11             else l = mid + 1;
12         }
13         return false;
14     }
15 }

 

别人三种方法总结:

  1. a square number is 1+3+5+7+... Time Complexity O(sqrt(N)) (Credit to lizhibupt, thanks for correcting this).
  2. binary search. Time Complexity O(logN)
  3. Newton Method. See [this wiki page][1]. Time Complexity is close to constant, given a positive integer.
 1 public boolean isPerfectSquare(int num) {
 2       if (num < 1) return false;
 3       for (int i = 1; num > 0; i += 2)
 4         num -= i;
 5       return num == 0;
 6     }
 7     
 8     public boolean isPerfectSquare(int num) {
 9       if (num < 1) return false;
10       long left = 1, right = num;// long type to avoid 2147483647 case
11     
12       while (left <= right) {
13         long mid = left + (right - left) / 2;
14         long t = mid * mid;
15         if (t > num) {
16           right = mid - 1;
17         } else if (t < num) {
18           left = mid + 1;
19         } else {
20           return true;
21         }
22       }
23     
24       return false;
25     }
26     
27     boolean isPerfectSquare(int num) {
28       if (num < 1) return false;
29       long t = num / 2 + 1; //or t = num as the begining
30       while (t * t > num) {
31         t = (t + num / t) / 2;
32       }
33       return t * t == num;
34     }

 

Leetcode: Valid Perfect Squares

原文:http://www.cnblogs.com/EdwardLiu/p/6097372.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!