[英]Given a list and a value of x, split it such that all items less than x came before items greater than or equal to x
I have a question.我有个问题。 Is there a more efficient way to solve this issue?
有没有更有效的方法来解决这个问题? I made it like below but i created 3 new Lists.
我做了如下所示,但我创建了 3 个新列表。
public List<Integer> divideListByX1(List<Integer> list, int x) {
List<Integer> beforeX = new ArrayList<>();
List<Integer> afterX = new ArrayList<>();
List<Integer> all = new ArrayList<>();
for (Integer integer : list) {
boolean b = (integer < x) ? beforeX.add(integer) : afterX.add(integer);
}
all.addAll(beforeX);
all.addAll(afterX);
return all;
}
Thanks for your help谢谢你的帮助
This can be done in-place in linear time using the Pivot operation of Quicksort:这可以使用 Quicksort 的 Pivot 操作在线性时间内就地完成:
public static void pivot(List<Integer> list, int pivot) {
int left = 0;
int right = list.size() - 1;
while (left < right) {
while (left < list.size() && list.get(left) < pivot) {
left++;
}
while (right >= 0 && list.get(right) >= pivot) {
right--;
}
if (left < right)
Collections.swap(list, left++, right--);
}
}
The following way is very slightly more efficient because it adds the numbers straight into the resulting list in one go, instead of using intermediate lists:下面的方法效率稍微高一点,因为它将数字直接添加到一个 go 的结果列表中,而不是使用中间列表:
public static List<Integer> divideListByX1(List<Integer> list, int x) {
Integer[] result = new Integer[list.size()];
int lowIndex = 0;
int highIndex = result.length - 1;
for (Integer n : list) {
if (n < x)
result[lowIndex++] = n;
else
result[highIndex--] = n;
}
return Arrays.asList(result);
}
The downside with that is that the "high numbers" part is not in the original order of the input list, but I guess that's not important.这样做的缺点是“高数字”部分不是输入列表的原始顺序,但我想这并不重要。
Also, here's a way to do it using Streams, but is probably not more efficient than your initial attempt:另外,这里有一种使用 Streams 的方法,但可能不会比您最初的尝试更有效:
public List<Integer> divideListByX1(List<Integer> list, int x) {
return list
.stream()
.collect(Collectors.partitioningBy(n -> n >= x))
.values()
.stream()
.flatMap(List::stream)
.toList();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.