633. Sum of Square Numbers 是否由兩個徹底平方數構成

[抄題]:面試

Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c.算法

Example 1:數據結構

Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5

 

Example 2:ide

Input: 3
Output: False

 [暴力解法]:oop

時間分析:優化

空間分析:n^2spa

 [優化後]:debug

時間分析:code

空間分析:nblog

[奇葩輸出條件]:

[奇葩corner case]:

[思惟問題]:

覺得同向型,其實對撞型,關鍵是能省空間 面試官喜歡

[一句話思路]:

對撞型,關鍵是能省空間 面試官喜歡

[輸入量]:空: 正常狀況:特大:特小:程序裏處理到的特殊狀況:異常狀況(不合法不合理的輸入):

[畫圖]:

[一刷]:

  1. while (i <= (int)Math.sqrt(c) && j >= 0)  有沒有等號,仍是須要寫了試試

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分鐘肉眼debug的結果]:

[總結]:

對撞型省時間

[複雜度]:Time complexity: O(n) Space complexity: O(1)

[英文數據結構或算法,爲何不用別的數據結構或算法]:

[關鍵模板化代碼]:

[其餘解法]:

[Follow Up]:

[LC給出的題目變變變]:

 

class Solution { public boolean judgeSquareSum(int c) { //cc
        if (c < 0) return false; //ini
        int i = 0, j = (int)Math.sqrt(c); //while loop
        while (i <= (int)Math.sqrt(c) && j >= 0) { if (i * i + j * j < c) i++; else if (i * i + j * j > c) j--; else return true; } return false; } }
View Code

 

 [代碼風格] :

相關文章
相關標籤/搜索