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:

Input: 3
Output: False

 [暴力解法]:

时间分析:

空间分析:n^2

 [优化后]:

时间分析:

空间分析:n

[奇葩输出条件]:

[奇葩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

 

 [代码风格] :

posted @ 2018-05-03 16:23  苗妙苗  阅读(376)  评论(0编辑  收藏  举报