Skip to content

Files

162 lines (128 loc) · 3.16 KB

File metadata and controls

162 lines (128 loc) · 3.16 KB

中文文档

Description

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

Solutions

The picture above shows the relationship between a, b, and c. This question is actually looking up c in this table

From the upper right corner of the table, it is not difficult to find that it is similar to a binary search tree, so just start from the upper right corner and search according to the law of the binary search tree

Python3

class Solution(object):
    def judgeSquareSum(self, c):
        i, j = 0, int(math.sqrt(c))
        while i <= j:
            s = i * i + j * j
            if s < c:
                i += 1
            elif s > c:
                j -= 1
            else:
                return True
        return False

Java

class Solution {
    public boolean judgeSquareSum(int c) {
        int i = 0, j = (int) Math.sqrt(c);
        while (i <= j) {
            int s = i * i + j * j;
            if (s < c) {
                ++i;
            } else if (s > c) {
                --j;
            } else {
                return true;
            }
        }
        return false;
    }
}

TypeScript

function judgeSquareSum(c: number): boolean {
    let a = 0, b = Math.floor(Math.sqrt(c));
    while (a <= b) {
        let sum = a ** 2 + b ** 2;
        if (sum == c) return true;
        if (sum < c) {
            ++a;
        } else {
            --b;
        }
    }
    return false;
};

C++

class Solution {
public:
    bool judgeSquareSum(int c) {
        long i = 0, j = (long) sqrt(c);
        while (i <= j) {
            long s = i * i + j * j;
            if (s < c) ++i;
            else if (s > c) --j;
            else return true;
        }
        return false;
    }
};

Go

func judgeSquareSum(c int) bool {
	i, j := 0, int(math.Sqrt(float64(c)))
	for i <= j {
		s := i*i + j*j
		if s < c {
			i++
		} else if s > c {
			j--
		} else {
			return true
		}
	}
	return false
}

...