forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RemoveDuplicateElement.java
93 lines (64 loc) · 1.85 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
85
86
87
88
89
90
91
92
93
import java.util.Scanner;
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) {
// taking the input from the user
Scanner sc = new Scanner(System.in);
System.out.print("Enter the length of the array : ");
int n = sc.nextInt();
int a[] = new int[n];
System.out.println("Enter the values for the array elements : ");
// taking the values for the array from the user
for(int i=0; i<n; i++)
{
a[i] = sc.nextInt();
}
n = DuplicateElement(a,n);
// print the updated array
for (int i=0; i<n; i++){
System.out.print(a[i] + " ");
}
}
}
/*
Example :
Input:
Enter the length of the array : 4
Enter the values for the array elements :
1 1 2 2
Output:
1 2
*/