LeetCode 367. Valid Perfect Square

原题链接在这里:https://leetcode.com/problems/valid-perfect-square/

题目:

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, 看mid*mid == num, 若等于就是perfect square了. 若是大于就在[l, mid-1]区间找. 若是小于就在[mid+1, r]区间找.

注意overflow, 若num = Integer.MAX_VALUE, 那么mid*mid肯定overflow了. 所以mid 和 square都是long型.

Time Complexity: O(logn), n =num.

Space:O(1).

AC Java:

 1 public class Solution {
 2     public boolean isPerfectSquare(int num) {
 3         long l = 1; 
 4         long r = num;
 5         
 6         while(l <= r){
 7             long mid = l+(r-l)/2;
 8             long square = mid*mid;
 9             if(square == num){
10                 return true;
11             }else if(square > num){
12                 r = mid-1;
13             }else{
14                 l = mid+1;
15             }
16         }
17         return false;
18     }
19 }

类似Sqrt(x).

posted @ 2017-01-30 10:28  Dylan_Java_NYC  阅读(296)  评论(0编辑  收藏  举报