How to remove only one max (min) from a list using Java 8 stream API in O(N) time and O(C) space complexity

末鹿安然 提交于 2019-12-22 14:17:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!