【LeetCode】633. Sum of Square Numbers

Difficulty: Easy

 More:【目錄】LeetCode Java實現html

Description

https://leetcode.com/problems/sum-of-square-numbers/submissions/java

Given a non-negative integer c, your task is to decide whether there're two integers aand b such that a2 + b2 = c.ide

Example 1:post

Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5

 

Example 2:ui

Input: 3
Output: False

Intuition

Using two pointers: One starts from the beginning, the other starts from the end.code

It's very similar to Two Sum II - Input array is sortedhtm

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)blog

Space complexity :  O(1)ip

What I've learned

1.The use of two pointers.ci

 

 More:【目錄】LeetCode Java實現

相關文章
相關標籤/搜索