-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveDuplicates.java
More file actions
116 lines (93 loc) · 1.67 KB
/
Copy pathRemoveDuplicates.java
File metadata and controls
116 lines (93 loc) · 1.67 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
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
public class RemoveDuplicates
{
public static void main(String[] args)
{
RemoveDuplicates n = new RemoveDuplicates();
int[] x = {1,1,2};
System.out.println(n.removeDuplicates(x));
}
public int removeDuplicates(int[] A) {
// only 1 item
if(A.length == 1)
return 1;
// insertion sort in place
for(int i = 1; i < A.length; i++)
{
int j = i;
while(j > 0 && A[j-1] > A[j])
{
int temp = A[j-1];
A[j - 1] = A[j];
A[j] = temp;
j--;
}
}
int count = 0;
boolean first = true;
// go across ignoring duplicates
for(int i = 1; i < A.length; i++)
{
if(first)
{
count++;
}
if(A[i] == A[i-1])
{
first = false;
continue;
}
else
first = false;
count++;
// 1 1 2 3 4 5 5 5
}
return count;
}
public int[] mergesort(int[] A)
{
if(A.length <= 1)
return A;
int[] l = new int[A.length / 2];
int[] r = new int[(int) Math.ceil(A.length / 2)];
for(int i = 0; i < A.length / 2; i++)
l[i] = A[i];
for(int i = 0; i < (int) Math.ceil(A.length / 2); i++)
r[i] = A[A.length / 2 + i];
l = mergesort(l);
r = mergesort(r);
return merge(l, r);
}
public int[] merge(int[] a, int[] b)
{
int[] c = new int[a.length + b.length];
int ai = 0, bi = 0, ci = 0;
while(ai < a.length && bi < b.length)
{
if(a[ai] < b[bi])
{
c[ci] = a[ai];
ci++;
ai++;
}
else if(a[ai] >= b[bi])
{
c[ci] = b[bi];
bi++;
ci++;
}
}
while(ai < a.length)
{
c[ci] = a[ai];
ai++;
ci++;
}
while(bi < b.length)
{
c[ci]= b[bi];
bi++;
ci++;
}
return c;
}
}