码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Sum of Square Numbers

时间:2017-09-18 14:57:10      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:return   bsp   time   java   log   points   else   false   targe   

原题链接在这里: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

标签:return   bsp   time   java   log   points   else   false   targe   

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/7542698.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!