国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

[LeetCode] Valid Perfect Square

acrazing / 2008人閱讀

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;
    }
}

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/64981.html

相關文章

  • [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

    摘要:動態規劃法建立空數組從到每個數包含最少平方數情況,先所有值為將到范圍內所有平方數的值賦兩次循環更新,當它本身為平方數時,簡化動態規劃法四平方和定理法 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 完美平方數

    摘要:動態規劃復雜度時間空間思路如果一個數可以表示為一個任意數加上一個平方數,也就是,那么能組成這個數最少的平方數個數,就是能組成最少的平方數個數加上因為已經是平方數了。 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

    摘要:題目要求判斷一個數字最少由幾個平方數的和構成。思路一暴力遞歸要想知道什么樣的組合最好,暴力比較所有的結果就好啦。當然,效率奇差。代碼如下思路三數學統治一切這里涉及了一個叫做四平方定理的內容。有興趣的可以去了解一下這個定理。 題目要求 Given a positive integer n, find the least number of perfect square numbers (...

    reclay 評論0 收藏0

發表評論

0條評論

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