forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRemoveDuplicateElement.java
84 lines (61 loc) · 1.58 KB
/
RemoveDuplicateElement.java
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/**
*
* Remove duplicate elements from sorted Array
*
* Example:
* Input (To be used only for expected output) :
* 2
* 9
* 1, 2, 2, 3, 4, 4, 4, 5, 5
* 3
* 1 2 2
* Output
* 1, 2, 3, 4, 5
* 1 2
*/
public class RemoveDuplicateElement {
/**
*
* Method 1 Using extra space
*
*/
// The function remove the duplicate element
// Function take two argument array 'a' of size 'n'.
static int DuplicateElement(int[] a, int n){
// check if array is empty or it has only 1 element
if (n==0 || n==1)
return n;
// Now we create an temporary array of size an
// it stores the unique element
int[] temp = new int[n];
int j=0;
// start traversing the array
for (int i=0; i<n-1; i++){
// If current element is not equal
// to next element then store that
// current element
if (a[i] != a[i+1]){
temp[j++] = a[i];
}
}
// Store the last element as whether
// it is unique or repeated, it hasn't
// stored previously
temp[j++] = a[n-1];
// modify original array
for (int i=0; i<j; i++){
a[i] = temp[i];
}
return j;
}
public static void main(String[] args) {
int a[] = {1, 2, 2, 3, 4, 4, 4, 5, 5};
int n = a.length;
n = DuplicateElement(a,n);
// print the updated array
for (int i=0; i<n; i++){
System.out.print(a[i] + " ");
// output - 1 2 3 4 5
}
}
}