1. 程式人生 > >Leetcode——633. Sum of Square Numbers

Leetcode——633. Sum of Square Numbers

題目原址

題目描述

Given a non-negative integer c, your task is to decide whether there’re two integers a and b such that a*a+ b*b = c.

Example1:

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

Example2:

Input: 3
Output: False

解題思路

根據二插排序的思想,從中間開始進行判斷。因為判斷數是否是數a*a + b*b的和。所以a和b一定比所判斷的數c開根號要小,所以a的值應該從0開始依次遞增,b應該從c的平方根開始依次遞減。通過迴圈進行判斷,直到a>b還沒沒有找到符合條件的值,則返回fasle;迴圈體重,如果當前的判斷結果小於判斷的數c,則將a值遞增,否則將b值遞減

AC程式碼

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