Removal of negative numbers from an array in Java

user7117165 :

My objective is to remove all negative numbers from an array in Java.

I have written the below code. How do I improve the complexity of code or is there a good algorithm?

public static void main(String[] args) {
    int[] array = { 1, -3, 4, -9, 3, 4, 70, -10, 0, 7 };
    System.out.println(Arrays.toString(removeNegativeNumbers(array)));
}

public static int[] removeNegativeNumbers(int[] num) {
    List<Integer> list = new ArrayList<>();
    for (int n : num) {
        if (n >= 0) {
            list.add(n);
        }
    }
    int[] result = new int[list.size()];
    for (int i = 0; i < result.length; i++) {
        result[i] = list.get(i).intValue();
    }
    return result;
}
Kaidul :

How do I improve the complexity of code or is there a good algorithm?

Here is a linear O(n) algorithm with constant space (neglecting the space we need for output array). When an element is non-negative, copy the element and advance both output array and input array seeker. And when the element is negative, advance only the input array seeker(indx) and avoid copying to output array.

public static int[] removeNegativeNumbers(int[] num) {
    int[] output = new int[num.length];
    int k = 0;
    for(int i = 0; i < num.length; i++) {
       if(num[i] >= 0) {
           output[k++] = num[i];
       }
    }
    return Arrays.copyOfRange(output, 0, k);
}

Space Efficient Solution

You can make the algorithm in-place by transforming the input array to hold output like insertion sort way to avoid the space overhead of output array.

public static int removeNegativeNumbers(int[] num) {
    int k = 0;
    for(int i = 0; i < num.length; i++) {
       if(num[i] >= 0) {
           num[k++] = num[i];
       }
    }
    // Now input array is holding the output data
    // Return the length of output array
    return k;
}

// Usage: int newLen = removeNegativeNumbers(array);

This is called two pointers technique, very simple yet useful to solve many classical puzzles like Array de-duplication, merging two sorted arrays, intersection of two sorted arrays etc.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=447996&siteId=1