开发者

How to remove from an array using recursion in Java

How to remove from an array using recursion in Java?

the array can be in any length and with any integers.

You may not use loops (while,for etc.)

for example

[2][4][2][0][9]

should print (2 4 0 9)开发者_JAVA技巧

thanks for your assistance


You can't remove elements from an array in Java. Not with recursion, not with loops.


I am assuming here you don't actually want to remove the element [as @aioobe mentioned, it cannot be done], but you actually want to: "print all elements in the array, without duplicates". [I assume it from the example, you mention you want to print the specified output].

The way to do it is maintain a Set containing all elements you have already encountered, and print an element if and only if you encounter it and it is not in the set.

The recursion part will probably be: always handle the i element (arr[i]), and stop when i == arr.length. don't forget to increase i in each recursive call.

should look something like that:

public static void printNoDupes(int[] arr,int i,Set<Integer> seen) {
    if (i == arr.length) return;
    if (!seen.contains(arr[i])) {
        System.out.print(arr[i] + " ");
        seen.add(arr[i]);
    }
    printNoDupes(arr,i+1,seen);
}
public static void printNoDupes(int[] arr) { 
    printNoDupes(arr,0,new HashSet<Integer>());
    System.out.println();
}


Sort the array and then use recursion to remove element if it is same as the element previously found element / argument that indicates previous unique element.

And as others said, you can't remove elements from original array, you need to copy the elements that should be kept to a new array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜