633. 平方数之和(中等)

csdn推荐

633. 平方数之和

1. 题目描述

题目中转:633. 平方数之和

2.详细题解

本题是167. 两数之和 II - 输入有序数组(中等)题目的变型,由两数之和变为两数平方之和,判断是否存在满足条件的两个整数a和b,使之平方之和等于给定的整数c。

对于给定整数c,a和b最小值为0,最大值为c的平方根,因此,两个双指针的初始值分别为0和c的平方根(取整数),算法如下:

3.代码实现 3.1 Python

import math
class Solution:
    def judgeSquareSum(self, c: int) -> bool:
        left, right = 0 , int(math.sqrt(c))
        res = False
        while left <= right:
            sum = left ** 2 + right ** 2
            if sum == c:
                res = True
                break
            elif sum > c:
                right -= 1
            else:
                left += 1
        return res

3.2 Java 内存溢出溢出代码

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

调整整数数据类型,重新debug代码:

正确代码与截图

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

执行用时不必过于纠结,对比可以发现,对于python和java完全相同的编写,java的时间一般是优于python的;至于编写的代码的执行用时击败多少对手,执行用时和网络环境、当前提交代码人数等均有关系,可以尝试完全相同的代码多次执行用时也不是完全相同,只要确保自己代码的算法时间复杂度满足相应要求即可,也可以通过点击分布图查看其它coder的code。

文章来源:https://blog.csdn.net/weixin_38979465/article/details/139987810



微信扫描下方的二维码阅读本文

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容