如何在不创建存储过程的情况下在oracle中实现以下功能?
数据集:
question_id element_id
1 7
1 8
2 9
3 10
3 11
3 12
预期结果:
question_id element_id
1 7,8
2 9
3 10,11,12
你可以利用弗洛伊德的循环寻找算法,也被称为乌龟和兔子算法。
这个想法是有两个引用列表,并以不同的速度移动它们。一个1节点向前移动一个,另一个2节点移动。
如果链表有一个循环,他们一定会见面。
否则两个引用(或他们next)中的任何一个都会变成null。
实现该算法的Java函数:
boolean hasLoop(Node first) {
if(first == null) // list does not exist..so no loop eithe
return false;
Node slow, fast; // create two references.
slow = fast = first; // make both refer to the start of the list
while(true) {
slow = slow.next; // 1 hop
if(fast.next != null)
fast = fast.next.next; // 2 hops
else
return false; // next node null => no loop
if(slow == null || fast == null) // if either hits null..no loop
return false;
if(slow == fast) // if the two ever meet...we must have a loop
return true;
}
}
面是Fast / Slow解决方案的一个改进,它可以正确处理奇数长度的列表并提高清晰度。
boolean hasLoop(Node first) {
Node slow = first;
Node fast = first;
while(fast != null && fast.next != null) {
slow = slow.next; // 1 hop
fast = fast.next.next; // 2 hops
if(slow == fast) // fast caught up to slow, so there is a loop
return true;
}
return false; // fast reached null, so the list terminates
}