小编CSn*_*bie的帖子

从原始 IP 字符串计算所有有效 IP 地址

我现在正在解决 leetcode 问题 93。恢复 IP 地址。

这是网址链接:https : //leetcode.com/problems/restore-ip-addresses/

描述如下: 给定一个只包含数字的字符串 s。返回可以从 s 获取的所有可能的有效 IP 地址。您可以按任何顺序退回它们。

一个有效的 IP 地址正好由四个整数组成,每个整数都在 0 到 255 之间,用单点分隔,不能有前导零。例如,“0.1.2.201”和“192.168.1.1”是有效IP地址,“0.011.255.245”、“192.168.1.312”和“192.168@1.1”是无效IP地址。

然而,当我试图通过回溯解决我的问题时,我无法弄清楚我总是返回一个空的 ArrayList 的原因。我仔细检查了我的基本情况和我的递归,但仍然找不到错误。任何帮助将不胜感激,谢谢!

public List<String> restoreIpAddresses(String s) {
        List<String> res = new ArrayList<>();
        if(s.length() == 0){
            return res;
        }
        int[] path = new int[4];
        snapshotIP(res,s,0,path,0);
        return res;
    }
    
    public void snapshotIP(List<String> res, String s, int index, int[] path, int segment){
        if(segment == 4 && index == s.length()){
            res.add(path[0]+"."+path[1]+"."+path[2]+"."+path[3]);
            return;
        }
        else if(segment == 4 || index …
Run Code Online (Sandbox Code Playgroud)

java backtracking

2
推荐指数
1
解决办法
341
查看次数

使用二分查找查找数字的平方根

我尝试使用二分搜索来查找整数的平方根,但有些我无法通过一些测试用例。

我能够传递 mySqrt(4) = 2,但无法传递 mySqrt(2147395599)

关于我搞砸的地方有什么想法吗?

public static int mySqrt(int x) {
        int left = 0;
        int right = x;

        if(x < 2){
            return x;
        }
        while(left < right){
            int mid = left + ((right - left) / 2);

            if(mid * mid == x){
                return mid;

            }
            else if(mid * mid < x){
                left = mid + 1;
            }
            else{
                right = mid; 
            }
        }
        return left - 1;
    }
Run Code Online (Sandbox Code Playgroud)

java binary-search square-root

1
推荐指数
1
解决办法
4051
查看次数

标签 统计

java ×2

backtracking ×1

binary-search ×1

square-root ×1