Leetcode | Sum of Square Numbers

Description:

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

Example:

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

Input: c = 3
Output: false

Ideas:

We all know that the sqrt of an integer must be small or equal with the orig integer. So I wanna make a list traverse from zero to int(sqrt( c )). Then judge whether there exist a sum of the squares of two numbers equals with c. However this way exceeds time limit.

My code:

from math import sqrt
class Solution(object):
    def judgeSquareSum(self, c):
        """
        :type c: int
        :rtype: bool
        """
        idx = int(sqrt(c))+1
        c_list = [i for i in range(idx)]
        for i in c_list:
            for j in reversed(c_list):
                if i*i + j*j == c:
                    return True
        return False

Execution takes:out of time limit

The others code:

i 从 0 开始
j 从可取的最大数 int(math.sqrt( c )) 开始
total = i * i + j * j
total > c: j = j - 1,将 total 值减小
total < c: i = i + 1,将 total 值增大
total == c:返回 True

def judgeSquareSum(self, c):
        """
        :type c: int
        :rtype: bool
        """
        j = int(math.sqrt(c))
        i = 0
        while i <= j:
            total = i * i + j * j
            if total > c:
                j = j - 1
            elif total < c:
                i = i + 1
            else:
                return True
        return False

Execution takes:76 ms
Memery consumption:12.9 MB

summary

It seems that I haven’t consider time complexity, maybe i have forgotten what time complexity is.

你可能感兴趣的:(Leetcode)