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 }
原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/7542698.html