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://m.hztianpu.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...
摘要:動(dòng)態(tài)規(guī)劃法建立空數(shù)組從到每個(gè)數(shù)包含最少平方數(shù)情況,先所有值為將到范圍內(nèi)所有平方數(shù)的值賦兩次循環(huán)更新,當(dāng)它本身為平方數(shù)時(shí),簡化動(dòng)態(tài)規(guī)劃法四平方和定理法 Problem Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) whi...
摘要:動(dòng)態(tài)規(guī)劃復(fù)雜度時(shí)間空間思路如果一個(gè)數(shù)可以表示為一個(gè)任意數(shù)加上一個(gè)平方數(shù),也就是,那么能組成這個(gè)數(shù)最少的平方數(shù)個(gè)數(shù),就是能組成最少的平方數(shù)個(gè)數(shù)加上因?yàn)橐呀?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...
摘要:題目要求判斷一個(gè)數(shù)字最少由幾個(gè)平方數(shù)的和構(gòu)成。思路一暴力遞歸要想知道什么樣的組合最好,暴力比較所有的結(jié)果就好啦。當(dāng)然,效率奇差。代碼如下思路三數(shù)學(xué)統(tǒng)治一切這里涉及了一個(gè)叫做四平方定理的內(nèi)容。有興趣的可以去了解一下這個(gè)定理。 題目要求 Given a positive integer n, find the least number of perfect square numbers (...
閱讀 2050·2023-04-26 01:59
閱讀 3334·2021-10-11 11:07
閱讀 3371·2021-09-22 15:43
閱讀 3456·2021-09-02 15:21
閱讀 2659·2021-09-01 10:49
閱讀 956·2019-08-29 15:15
閱讀 3167·2019-08-29 13:59
閱讀 2891·2019-08-26 13:36