问题
Here is a code for removing only one of the max values (in this case the first one, but this is irrelevant) from the list. It is O(n)
in time and O(n)
in space (beyond the input).
public List<Integer> removeOneOfTheMax(List<Integer> nums) {
int max = Integer.MIN_VALUE;
int maxIndex = -1;
Iterator<Integer> it = nums.iterator();
for (int i = 0; it.hasNext(); i++) {
Integer temp = it.next();
if (max < temp) {
maxIndex = i;
max = temp;
}
}
nums.remove(maxIndex);
return nums;
}
1. What would be the equivalent of the method using the Java 8 stream API? I would like to preserve the time and space complexity, so no sorting is allowed.
2. Actually, if you pass a LinkedList
into the above code the space complexity would be O(C)
(again, beyond the input), but as far as I understand the .stream()
creates an additional data structure so a stream API equivalent must be at least O(N)
in space. Correct me if I am wrong.
回答1:
The stream solution could look like this:
int maxIndex = IntStream.range(1, nums.size()).reduce(0, (i, j) -> {
int left = nums.get(i);
int right = nums.get(j);
return Integer.max(left, right) == left ? i : j;
});
nums.remove(maxIndex);
Underneath there is going to be a Spliterator
.
The stream operation itself is not going to create additional data structures.
来源:https://stackoverflow.com/questions/41892374/how-to-remove-only-one-max-min-from-a-list-using-java-8-stream-api-in-on-tim