为简单起见,假设我有一个ArrayList其索引正好包含一位整数。例如:
6 4 5 6 0 6 3 4 1 6 1 6 0 6 8 3
Run Code Online (Sandbox Code Playgroud)
I would like to filter out all occurrences of the sublist 6 0 6, such that the new list becomes:
6 4 5 3 4 1 6 1 8 3
Run Code Online (Sandbox Code Playgroud)
Is there any way of doing this? Using ListIterator doesn't seem to work for me, because I have to consider three consecutive elements collectively and I'm honestly not sure how to do that.
Here's a skeleton of the method I have implemented:
public static void filterList(ArrayList<Integer> list) {
ListIterator<Integer> iterator = list.listIterator();
int elem;
while (iterator.hasNext()) {
// Remove any sublist of 6 0 6
}
}
Run Code Online (Sandbox Code Playgroud)
Edit: Again, for simplicity, let's assume there won't be cases where we have 60606 or similar.
您可以使用以下方法创建高效且简洁的 O(nm) 解决方案Collections.indexOfSubList:
public static void removeAllSubList(List<?> list, List<?> subList) {
// find first occurrence of the subList in the list, O(nm)
int i = Collections.indexOfSubList(list, subList);
// if found
if (i != -1) {
// bulk remove, O(m)
list.subList(i, i + subList.size()).clear();
// recurse with the rest of the list
removeAllSubList(list.subList(i, list.size()), subList);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6542 次 |
| 最近记录: |