-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemDup.java
More file actions
59 lines (46 loc) · 1.91 KB
/
RemDup.java
File metadata and controls
59 lines (46 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Java program to remove duplicates from this array. You don't
* need to physically delete duplicate elements, replacing with null, or
* empty or default value is ok.
*
* @author http://javarevisited.blogspot.com
*/
public class TechnicalInterviewTest {
private static final Logger logger = LoggerFactory.getLogger(TechnicalInterviewTest.class);
public static void main(String args[]) {
int[][] test = new int[][]{
{1, 1, 2, 2, 3, 4, 5},
{1, 1, 1, 1, 1, 1, 1},
{1, 2, 3, 4, 5, 6, 7},
{1, 2, 1, 1, 1, 1, 1},};
for (int[] input : test) {
System.out.println("Array with Duplicates : " + Arrays.toString(input));
System.out.println("After removing duplicates : " + Arrays.toString(removeDuplicates(input)));
}
}
/*
* Method to remove duplicates from array in Java, without using
* Collection classes e.g. Set or ArrayList. Algorithm for this
* method is simple, it first sort the array and then compare adjacent
* objects, leaving out duplicates, which is already in the result.
*/
public static int[] removeDuplicates(int[] numbersWithDuplicates) {
// Sorting array to bring duplicates together
Arrays.sort(numbersWithDuplicates);
int[] result = new int[numbersWithDuplicates.length];
int previous = numbersWithDuplicates[0];
result[0] = previous;
for (int i = 1; i < numbersWithDuplicates.length; i++) {
int ch = numbersWithDuplicates[i];
if (previous != ch) {
result[i] = ch;
}
previous = ch;
}
return result;
}
}
Read more: https://javarevisited.blogspot.com/2014/01/how-to-remove-duplicates-from-array-java-without-collection-API.html#ixzz6DCSX5Qep