首页 > 其他 > 详细

【LeetCode】633. Sum of Square Numbers

时间:2019-09-27 23:00:55      阅读:96      评论:0      收藏:0      [点我收藏+]

Difficulty: Easy

 More:【目录】LeetCode Java实现

Description

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

Example 1:

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

 

Example 2:

Input: 3
Output: False

Intuition

Using two pointers: One starts from the beginning, the other starts from the end.

It‘s very similar to Two Sum II - Input array is sorted

Solution

    public boolean judgeSquareSum(int c) {
        if(c<0)
            return false;
        int i=0;
        int j=(int)Math.sqrt(c);
        while(i<=j){
            int ans=i*i+j*j;
            if(ans<c){
                i++;
            }else if(ans>c){
                j--;
            }else{
                return true;
            }
        }
        return false;
    }

  

Complexity

Time complexity : O(n)

Space complexity :  O(1)

What I‘ve learned

1.The use of two pointers.

 

 More:【目录】LeetCode Java实现

 

【LeetCode】633. Sum of Square Numbers

原文:https://www.cnblogs.com/yongh/p/11600830.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!