More:【目录】LeetCode Java实现
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
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
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; }
Time complexity : O(n)
Space complexity : O(1)
1.The use of two pointers.
More:【目录】LeetCode Java实现
【LeetCode】633. Sum of Square Numbers
原文:https://www.cnblogs.com/yongh/p/11600830.html