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; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/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...
摘要:動態(tài)規(guī)劃法建立空數(shù)組從到每個數(shù)包含最少平方數(shù)情況,先所有值為將到范圍內(nèi)所有平方數(shù)的值賦兩次循環(huán)更新,當(dāng)它本身為平方數(shù)時,簡化動態(tài)規(guī)劃法四平方和定理法 Problem Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) whi...
摘要:動態(tài)規(guī)劃復(fù)雜度時間空間思路如果一個數(shù)可以表示為一個任意數(shù)加上一個平方數(shù),也就是,那么能組成這個數(shù)最少的平方數(shù)個數(shù),就是能組成最少的平方數(shù)個數(shù)加上因為已經(jīng)是平方數(shù)了。 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...
摘要:題目要求判斷一個數(shù)字最少由幾個平方數(shù)的和構(gòu)成。思路一暴力遞歸要想知道什么樣的組合最好,暴力比較所有的結(jié)果就好啦。當(dāng)然,效率奇差。代碼如下思路三數(shù)學(xué)統(tǒng)治一切這里涉及了一個叫做四平方定理的內(nèi)容。有興趣的可以去了解一下這個定理。 題目要求 Given a positive integer n, find the least number of perfect square numbers (...
閱讀 1973·2023-04-26 01:59
閱讀 3276·2021-10-11 11:07
閱讀 3309·2021-09-22 15:43
閱讀 3388·2021-09-02 15:21
閱讀 2572·2021-09-01 10:49
閱讀 912·2019-08-29 15:15
閱讀 3100·2019-08-29 13:59
閱讀 2839·2019-08-26 13:36