Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 查找子列表的索引_Java_Algorithm - Fatal编程技术网

Java 查找子列表的索引

Java 查找子列表的索引,java,algorithm,Java,Algorithm,算法问题。假设我们有一个列表1,2,3,4,5和一个子列表2,3,算法应该返回1,因为子列表从索引1开始。如果指定的子列表不存在,则算法应返回-1 我们有一个定义的节点数据结构,如下所示 Node.java private static class Node { public Node(int value) { this.value = value; this.next = null; } int value; Node nex

算法问题。假设我们有一个列表
1,2,3,4,5
和一个子列表
2,3
,算法应该返回1,因为子列表从索引1开始。如果指定的子列表不存在,则算法应返回-1

我们有一个定义的
节点
数据结构,如下所示

Node.java

private static class Node {

    public Node(int value) {
        this.value = value;
        this.next = null;
    }

    int value;
    Node next;
}
我提出了以下算法,但我很好奇它在性能方面是否比这更好

public static int findSublistIndex(MyLinkedList list, MyLinkedList sublist) {
    if (list.head == null || sublist.head == null) {
        return -1;
    }

    int index = -1;

    for (Node l = list.head; l != null; l = l.next) {
        index ++;

        // encountered a value that is equal to the first value of a sublist
        if (l.value == sublist.head.value) {
            Node n = l;

            // check the rest of the sublist
            for (Node s = sublist.head; s != null; s = s.next) {
                if (n.value == s.value && s.next == null) {
                    return index;
                } else if (n.value == s.value) {
                    n = n.next;
                } else {
                    // the pointer should be set to l here to skip repeating? l = n;? -- doesn't work!
                    break;
                }
            }
        }
    }

    return -1;
}
另外,我还想练习一些类似这样的列表算法问题。有这样问题的网站推荐吗?

更好的算法是。它用于执行子字符串搜索,也可用于您的案例。它的时间开销是O(n+k),因此它是一个线性算法,您的算法是O(nk),n是列表的长度,k是子列表的长度


更多的算法挑战或代码挑战,您可以在或

中找到,我投票将此问题作为离题题结束,因为它要求对工作算法进行审查,并建议练习编程的地方。@dasblinkenlight那么问题出在哪里?我要求对算法进行可能的改进。为什么不寻求建议在哪里练习呢……这个问题对于堆栈溢出来说是不合适的。请参阅发布类似问题。此外,对于站点来说,询问非站点资源建议的问题显然是非主题的。另外还有一个stack exchange站点专门针对此类问题创建。请注意,您的算法可以抛出NullPointerException