[LeetCode] 633. Sum of Square Numbers

Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c.

Example 1:
Input: c = 5
Output: true
Explanation: 1 * 1 + 2 * 2 = 5

Example 2:
Input: c = 3
Output: false

Example 3:
Input: c = 4
Output: true

Example 4:
Input: c = 2
Output: true

Example 5:
Input: c = 1
Output: true

Constraints:
0 <= c <= 231 - 1

平方数之和。

给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a^2 + b^2 = c 。

思路

给定一个数字 C,请判断是否存在另外两个数字 A 和 B,满足 A 平方 + B 平方 = C 平方。

思路是双指针逼近。根据题意,A 和 B 的范围一定比 C 的平方根要小,所以 A 和 B 的取值范围是 0 - Math.sqrt(C)。可以将 left = 0,right = Math.sqrt(C) 做二分,其余部分就是二分法题目的常规判断了。

复杂度

时间O(logn)
空间O(1)

代码

Java实现

class Solution {
    public boolean judgeSquareSum(int c) {
        long left = 0;
        long right = (long) Math.sqrt(c);
        long res = 0;
        while (left <= right) {
            res = left * left + right * right;
            if (res == c) {
                return true;
            } else if (res > c) {
                right--;
            } else {
                left++;
            }
        }
        return false;
    }
}
posted @ 2021-01-12 06:57  CNoodle  阅读(129)  评论(0)    收藏  举报