zoukankan      html  css  js  c++  java
  • [LeetCode] 633. Sum of Square Numbers

    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

    平方数之和。

    给定一个数字C,请判断是否存在另外两个数字A和B,满足A平方 + B平方 = C平方。

    思路是二分法。根据题意,A和B的范围一定比C的平方根要小,所以二分的范围是0 - Math.sqrt(C)。可以将 left = 0,right = Math.sqrt(C) 做二分,其余部分就是二分法题目的常规判断了。

    时间O(logn)

    空间O(1)

    Java实现

     1 class Solution {
     2     public boolean judgeSquareSum(int c) {
     3         int left = 0;
     4         int right = (int) Math.sqrt(c);
     5         while (left <= right) {
     6             int cur = left * left + right * right;
     7             if (cur < c) {
     8                 left++;
     9             } else if (cur > c) {
    10                 right--;
    11             } else {
    12                 return true;
    13             }
    14         }
    15         return false;
    16     }
    17 }

    LeetCode 题目总结 

  • 相关阅读:
    CControlLayer
    CBiontCache
    CHero
    CWidgetMgr---cpp
    CWidgetMgr---H
    CXAnimation类
    CXAnimation.h动画类
    CXCommon.h工具类
    【leetcode】441. Arranging Coins
    【linux基础】关于ARM板子使用O3编译选项优化
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14265198.html
Copyright © 2011-2022 走看看