博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode633- Sum of Square Numbers- easy
阅读量:4576 次
发布时间:2019-06-08

本文共 1487 字,大约阅读时间需要 4 分钟。

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: 5Output: TrueExplanation: 1 * 1 + 2 * 2 = 5

 

Example 2:

Input: 3Output: 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
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;    }}

 

转载于:https://www.cnblogs.com/jasminemzy/p/7920760.html

你可能感兴趣的文章
JAVA_桥接模式
查看>>
C语言 strcpy,memcpy,memmove,memccpy函数
查看>>
C语言一个小程序的bug疑问 数组相关[已解决]
查看>>
几种排序算法(PHP版)
查看>>
数据库字段数据类型对索引的影响
查看>>
perl6的介绍与下载编译安装
查看>>
mesos cluster
查看>>
Altium Designer 中差分走线
查看>>
linux 解压缩命令
查看>>
GDUT校赛
查看>>
(HDU)1076 --An Easy Task(简单任务)
查看>>
团队精神与集体主义的区别?
查看>>
Spring Boot 入门(Spring Cloud方向)
查看>>
仿淘宝商品图片放大镜效果(鼠标移动上去会出现放大的图片,并且可以移动)...
查看>>
AngularJS(九):路由
查看>>
Google chrome浏览器HTML5 Beta项目, 未来Web前瞻!
查看>>
GPS.NET 和 GeoFramework开源了
查看>>
汇编:采用址表的方法编写程序实现C程序的switch功能
查看>>
AtiveMQ初次连接的 http error:503 连接错误 Prolem accessing /.Reason : Service Unavailable...
查看>>
OFO和摩拜共享单车
查看>>