LeetCode Valid Perfect Square
2017-01-30 10:28
501 查看
原题链接在这里: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
Example 1:
Example 2:
题解:
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:
类似Sqrt(x).
题目:
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).
相关文章推荐
- JavaScript中的深度克隆
- Codeforces Round #256 (Div. 2)-C. Painting Fence
- 前端分页功能的实现以及原理
- json数据操作
- React&Redux
- 276. Paint Fence
- Effective Java 读书笔记——39:必要时进行保护性拷贝
- jsp表单中上传文件 enctype="multipart/form-data"解释
- jquery defered 对象学习
- Effective Java 读书笔记——15:使可变性最小化
- JavaScript 雷达
- [转] 钉钉的H5性能优化方案
- Bootstrap表单构造器
- 『状态』驱动的世界:ReactiveCocoa
- jstl核心标签库和其他
- jsp_el内置对象pageContext和Cookie
- 3145: [Feyat cup 1.5]Str
- jquery tooltip插件
- JavaScript document.write 与 document.writeln 的区别
- bootstrap-table相关参数的解释