LeetCode Sum of Square Numbers

Posted Dylan_Java_NYC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Sum of Square Numbers相关的知识,希望对你有一定的参考价值。

原题链接在这里:https://leetcode.com/problems/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

题解:

在[0, (int)Math.sqrt(c)]区间内用two points夹比.

Time Complexity: O(sqrt(c)). Space: O(1).

AC Java:

 1 class Solution {
 2     public boolean judgeSquareSum(int c) {
 3         if(c < 0){
 4             return false;
 5         }
 6         
 7         int l = 0; 
 8         int r = (int)Math.sqrt(c);
 9         while(l<=r){
10             int cur = l*l + r*r;
11             if(cur == c){
12                 return true;
13             }else if(cur < c){
14                 l++;
15             }else if(cur > c){
16                 r--;
17             }
18         }
19         return false;
20     }
21 }

 

以上是关于LeetCode Sum of Square Numbers的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] Sum of Square Numbers

[leetcode-633-Sum of Square Numbers]

LeetCode 633. Sum of Square Numbers

[leetcode]633. Sum of Square Numbers

[LeetCode] Sum of Square Numbers 平方数之和

[LeetCode] 1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold 元素和小于等于阈值的