刷题(2): LeetCode 633. -- two pointers

leetcode 633. Sum of Square Numbers

这是一道easy题,但是在leetcode solution那里提供了很多种解法。这道题目其实很多解法都比较偏重数学知识,就是得到的结论需要数学推理。我不擅长数学,所以自己写的时候偏向于写比较直接的东西,不需要靠数学公式/理论的那种。

还有就是这道题目比较tricky的地方是,必须注意int的值的范围。take my solution as example.

solution: two pointers

class Solution {

    public boolean judgeSquareSum(int c) {

        long left =0, right = (int)Math.sqrt(c);

        while(left<=right) {

            long sum = left*left + right*right;

            if(sum == c) {

                return true;

            } else if(sum < c) {

                left++;

            } else {

                right --;

            }

        }

        return false;

    }

}


here left is long type, because when we have left*left + right*right, the result might be larger than the max value of integer in java, one can test using 2147483600. if we have left in int type, we must force change the result of (left*left) to long, so that the result of the sum can be long too.

time complexity: O(sqrt(c)), iterate once

space complexity: O(1) constant space

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • * Always remember to check the quality/availability of th...
    Morphiaaa阅读 743评论 0 0
  • 16宿命:用概率思维提高你的胜算 以前的我是风险厌恶者,不喜欢去冒险,但是人生放弃了冒险,也就放弃了无数的可能。 ...
    yichen大刀阅读 6,120评论 0 4
  • 公元:2019年11月28日19时42分农历:二零一九年 十一月 初三日 戌时干支:己亥乙亥己巳甲戌当月节气:立冬...
    石放阅读 6,930评论 0 2
  • 年纪越大,人的反应就越迟钝,脑子就越不好使,计划稍有变化,就容易手忙脚乱,乱了方寸。 “玩坏了”也是如此,不但会乱...
    玩坏了阅读 2,181评论 2 1
  • 感动 我在你的眼里的样子,就是你的样子。 相互内化 没有绝对的善恶 有因必有果 当你以自己的价值观幸福感去要求其他...
    周粥粥叭阅读 1,656评论 1 5