【leetcode】367. Valid Perfect Square
problem
solution:二分法;
class Solution { public: bool isPerfectSquare(int num) { int left = 1, right = num;// long mid = 0; while(left<=right) { mid = left + 0.5*(right - left); long t = mid*mid; if(t < num) left = mid+1; else if (t > num) right = mid-1; else return true; } return false; } };
solution2:
纯数学解法,利用到了这样一条性质,完全平方数是一系列奇数之和;
1 = 1 4 = 1 + 3 9 = 1 + 3 + 5 16 = 1 + 3 + 5 + 7 25 = 1 + 3 + 5 + 7 + 9 .... 1+3+...+(2n-1) = (2n-1 + 1)n/2 = n*n
时间复杂度为O(sqrt(n))
class Solution { public: bool isPerfectSquare(int num) { int i = 1; while(num>0) { num -= i; i +=2; } return num==0; } };
其他两种方法都出现超时的问题。
参考
1. Leetcode_367. Valid Perfect Square;
2. GrandYang;
完
各美其美,美美与共,不和他人作比较,不对他人有期待,不批判他人,不钻牛角尖。
心正意诚,做自己该做的事情,做自己喜欢做的事情,安静做一枚有思想的技术媛。
版权声明,转载请注明出处:https://www.cnblogs.com/happyamyhope/
心正意诚,做自己该做的事情,做自己喜欢做的事情,安静做一枚有思想的技术媛。
版权声明,转载请注明出处:https://www.cnblogs.com/happyamyhope/
浙公网安备 33010602011771号