Skip to content

Commit 516266f

Browse files
Added Remove Duplicates From Sorted Array.
1 parent ca1474e commit 516266f

1 file changed

Lines changed: 64 additions & 0 deletions

File tree

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package interview.google;
2+
3+
import java.util.ArrayList;
4+
import java.util.Iterator;
5+
6+
import org.junit.Test;
7+
8+
import junit.framework.TestCase;
9+
10+
/**
11+
* Link:
12+
* https://www.interviewbit.com/problems/remove-duplicates-from-sorted-array/
13+
*
14+
* @author shivam.maharshi
15+
*/
16+
public class RemoveDuplicatesFromSortedArray extends TestCase {
17+
18+
@Test
19+
public static void test() {
20+
ArrayList<Integer> l = new ArrayList<>();
21+
l.add(1);
22+
l.add(1);
23+
l.add(1);
24+
l.add(2);
25+
l.add(2);
26+
l.add(3);
27+
l.add(4);
28+
l.add(4);
29+
l.add(10);
30+
l.add(15);
31+
assertEquals(6, removeDuplicates(l));
32+
}
33+
34+
public static int removeDuplicates(ArrayList<Integer> a) {
35+
if (a == null || a.size() == 0)
36+
return 0;
37+
int i = 0, j = 1;
38+
while (j < a.size()) {
39+
if (a.get(i).intValue() != a.get(j).intValue())
40+
a.set(++i, a.get(j).intValue());
41+
j++;
42+
}
43+
return i + 1;
44+
}
45+
46+
/*
47+
* This is O(n^2) solution because it.remove is O(n).
48+
*/
49+
public static int removeDuplicatesIt(ArrayList<Integer> a) {
50+
if (a == null || a.size() == 0)
51+
return 0;
52+
Iterator<Integer> it = a.iterator();
53+
int c = it.next().intValue();
54+
while (it.hasNext()) {
55+
int n = it.next().intValue();
56+
if (n != c)
57+
c = n;
58+
else
59+
it.remove();
60+
}
61+
return a.size();
62+
}
63+
64+
}

0 commit comments

Comments
 (0)