633. Sum of Square Numbers

Description

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

Solution

Two-pointers, time O(sqrt(N)), space O(1)

注意high可以从sqrt(c)开始算起,不用从c开始哦!

class Solution {
    public boolean judgeSquareSum(int c) {
        int low = 0;
        int high = (int) Math.sqrt(c);
        
        while (low <= high) {
            int sum = low * low + high * high;
            
            if (sum == c) {
                return true;
            } else if (sum < c) {
                ++low;
            } else {
                --high;
            }
        }
        
        return false;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,901评论 0 33
  • Easy Simple two pinters记住只需要遍历到sqrt(c)就可以了.
    greatseniorsde阅读 124评论 0 0
  • two sum 的换壳题 ,只是把原有在数组有序下相加为定值变成了平方的和相加为定值。
    namelessEcho阅读 252评论 0 0
  • 今天闲来无聊,本地了一个json读取,没想到,半天都是没获取到路径 后来发现我把json放到了一个实例文件夹中,不...
    wlysky阅读 5,082评论 0 1
  • 看到的两个场景: 1.十八岁的男孩,说:我能加一下你的微信吗? 十八岁的女孩,迟疑了一下,说:可以。 男孩边掏出手...
    心妍and敬阅读 224评论 0 0

友情链接更多精彩内容