[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平方 + B平方 = C平方。

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

时间O(logn)

空间O(1)

Java实现

 1 class Solution {
 2     public boolean judgeSquareSum(int c) {
 3         int left = 0;
 4         int right = (int) Math.sqrt(c);
 5         while (left <= right) {
 6             int cur = left * left + right * right;
 7             if (cur < c) {
 8                 left++;
 9             } else if (cur > c) {
10                 right--;
11             } else {
12                 return true;
13             }
14         }
15         return false;
16     }
17 }

LeetCode 题目总结 

原文地址:https://www.cnblogs.com/cnoodle/p/14265198.html