Problem
Given a positive integer num, write a function which returns True if num is a perfect square else False.
NoteDo not use any built-in library function such as sqrt.
ExamplesExample 1:
Input: 16 Returns: True
Example 2:
Input: 14 Returns: FalseSolution Newton"s method, close to O(1)
public class Solution { public boolean isPerfectSquare(int num) { if (num < 1) return false; long t = num/2+1; while (t*t > num) { t = (t+num/t)/2; } return t*t == num; } }Binary-Search method, O(logn)
public class Solution { public boolean isPerfectSquare(int num) { long start = 1, end = num; while (start <= end) { long mid = start + (end-start)/2; long t = mid * mid; if (t == num) return true; else if (t < num) start = mid+1; else end = mid-1; } return false; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/64981.html
Problem Given a positive integer num, write a function which returns True if num is a perfect square else False. Example For example:Given num = 16Returns True Solution class Solution { public boo...
摘要:動態規劃法建立空數組從到每個數包含最少平方數情況,先所有值為將到范圍內所有平方數的值賦兩次循環更新,當它本身為平方數時,簡化動態規劃法四平方和定理法 Problem Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) whi...
摘要:動態規劃復雜度時間空間思路如果一個數可以表示為一個任意數加上一個平方數,也就是,那么能組成這個數最少的平方數個數,就是能組成最少的平方數個數加上因為已經是平方數了。 Perfect Squares Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4...
Problem Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. Example 1: Input: n = 12Output: 3 Explanation: 12 = 4 + 4 + 4.Exampl...
摘要:題目要求判斷一個數字最少由幾個平方數的和構成。思路一暴力遞歸要想知道什么樣的組合最好,暴力比較所有的結果就好啦。當然,效率奇差。代碼如下思路三數學統治一切這里涉及了一個叫做四平方定理的內容。有興趣的可以去了解一下這個定理。 題目要求 Given a positive integer n, find the least number of perfect square numbers (...
閱讀 1949·2023-04-26 01:59
閱讀 3264·2021-10-11 11:07
閱讀 3295·2021-09-22 15:43
閱讀 3374·2021-09-02 15:21
閱讀 2549·2021-09-01 10:49
閱讀 901·2019-08-29 15:15
閱讀 3089·2019-08-29 13:59
閱讀 2829·2019-08-26 13:36