zoukankan      html  css  js  c++  java
  • leetcode633- Sum of Square Numbers- easy

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

    Example 1:

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

    Example 2:

    Input: 3
    Output: False

    算法:

    1. 递增法。用一个不断++1的数来算出所有平方数并存到set里,如果到某个点你发现c-i^2已经存在过set里了,那就说明你成功找到了。 但是会TLE

    2.双指针法。一个一开始指0,一个一开始指sqrt(n),然后根据平方和决定指针怎么移。这个一开始已经和答案很逼近所以时间复杂度低很多。

    3.确认互补数是不是整数法。很简洁。

    细节:Math.sqrt返回的是double,注意人工转换。

    实现1:

    class Solution {
        public boolean judgeSquareSum(int c) {
            Set<Integer> set = new HashSet<>();
            int n = 0;
            while (n * n <= c) {
                set.add(n * n);
                if (set.contains(c - n * n)) {
                    return true;
                }
                n++;
            }
            return false;
        }
    }

    实现2:

    class Solution {
        public boolean judgeSquareSum(int c) {
            if (c < 0) {
                return false;
            }
            int i = 0;
            int j = (int) Math.sqrt(c);
            while (i <= j) {
                int ss = i * i + j * j;
                if (ss == c) {
                    return true;
                } else if (ss < c) {
                    i++;
                } else {
                    j--;
                }
            }
            return false;
        }
    }

    实现3:

    class Solution {
        public boolean judgeSquareSum(int c) {
            for (int i = 0; i <= (int)Math.sqrt(c) + 1; i++) {
                if (Math.floor(Math.sqrt(c - i * i)) == Math.sqrt(c - i * i) ) {
                    return true;
                }
            }
            return false;
        }
    }
  • 相关阅读:
    mysql 常用函数
    JSP 分页代码
    day15(Mysql学习)
    day14(编码实战-用户登录注册)
    Bootstrap第3天
    Bootstrap第2天
    Bootstrap 第一天
    day13(JSTL和自定义标签&MVC模型&javaweb三层框架)
    label 对齐
    Alert提示框之后跳转指定页面
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7920760.html
Copyright © 2011-2022 走看看