【LeetCode】633. Sum of Square Numbers
Difficulty: Easy
More:【目录】LeetCode Java实现
Description
https://leetcode.com/problems/sum-of-square-numbers/submissions/
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
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) { int i=0, 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实现