天天看點

LeetCode每日一題13/?平方數之和

平方數之和

題目描述:

給定一個非負整數 c ,你要判斷是否存在兩個整數 a 和 b,使得 a2 + b2 = c 。

輸入輸出樣例

輸入:c = 5
輸出:true
解釋:1 * 1 + 2 * 2 = 5
           

題解:

本題為簡單題,類似于之前做過的兩數之和的題。同樣是運用雙指針同時從兩段向中間循環周遊求值。唯一要注意的一點是了解為何采用該方法不會少判。可以通過雙指針的本質或者類比成二維數組判斷查找來思考;參考教程:LeetCode精品題解

具體代碼

#include <iostream>
#include <cstring>
#include <algorithm>
#include <math.h>
#include <vector>
using namespace std;

class L663 {
public:
    bool judgeSquareSum(int c) {
        int low = 0;
        int high = sqrt(c);
        while (low <= high) {
            int sum = low * low + high * high;
            if (sum == c) {
                return true;
            }
            else if (sum < c) {
                low++;
            }
            else if (sum > c) {
                high--;
            }
        }
        return false;
    }
};
           

繼續閱讀