成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

[LeetCode] Valid Perfect Square

acrazing / 2016人閱讀

Problem

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.

Examples

Example 1:

Input: 16
Returns: True

Example 2:

Input: 14
Returns: False
Solution 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

相關(guān)文章

  • [LeetCode] 367. Valid Perfect Square

    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...

    sean 評論0 收藏0
  • [LintCode/LeetCode] Perfect Squares

    摘要:動態(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...

    sydMobile 評論0 收藏0
  • [Leetcode] Perfect Squares 完美平方數(shù)

    摘要:動態(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...

    Moxmi 評論0 收藏0
  • [LeetCode] 279. Perfect Squares

    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...

    mist14 評論0 收藏0
  • leetcode279. Perfect Squares

    摘要:題目要求判斷一個數(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 (...

    reclay 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<