Skip to content

Commit 6bea5ca

Browse files
Remove Duplicates from Sorted Array II
1 parent 0f30dc0 commit 6bea5ca

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,7 @@ Your ideas/fixes/algorithms are more than welcome!
191191
|89|[Gray Code](https://leetcode.com/problems/gray-code/)|[Solution](../../blob/master/src/stevesun/algorithms/GrayCode.java)|O(n) |O(1)|Medium|Bit Manipulation
192192
|86|[Partition List](https://leetcode.com/problems/partition-list/)|[Solution](../../blob/master/src/stevesun/algorithms/PartitionList.java)|O(?) |O(?)|Medium|
193193
|85|[Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/)|[Solution](../../blob/master/src/stevesun/algorithms/MaximalRectangle.java)|O(m*n) |O(n)|Hard|DP
194+
|80|[Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)|[Solution](../../blob/master/src/stevesun/algorithms/RemoveDuplicatesfromSortedArrayII.java)|O(n) |O(n)|Medium|
194195
|79|[Word Search](https://leetcode.com/problems/word-search/)|[Solution](../../blob/master/src/stevesun/algorithms/WordSearch.java)|O(m*n*l) ? |O(m*n)|Medium|Backtracking/DFS
195196
|78|[Subsets](https://leetcode.com/problems/subsets/)|[Solution](../../blob/master/src/stevesun/algorithms/Subsets.java)|O(n^2) ? |O(1)|Medium|Backtracking
196197
|76|[Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/)|[Solution](../../blob/master/src/stevesun/algorithms/MinimumWindowSubstring.java)|O(n)|O(k)|Hard|Two Pointers
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package stevesun.algorithms;
2+
3+
import java.util.ArrayList;
4+
5+
/**
6+
* Follow up for "Remove Duplicates":
7+
What if duplicates are allowed at most twice?
8+
9+
For example,
10+
Given sorted array nums = [1,1,1,2,2,3],
11+
12+
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.
13+
*/
14+
public class RemoveDuplicatesfromSortedArrayII {
15+
16+
public int removeDuplicates(int[] nums) {
17+
int counter = 0;
18+
int len = nums.length;
19+
if (len == 0) {
20+
return 0;
21+
}
22+
if (len == 1) {
23+
return 1;
24+
}
25+
if (len == 2) {
26+
return 2;
27+
}
28+
29+
ArrayList<Integer> a = new ArrayList();
30+
a.add(nums[0]);
31+
a.add(nums[1]);
32+
for (int i = 2; i < len; i++) {
33+
if (nums[i] != nums[i - 1]) {
34+
a.add(nums[i]);
35+
} else if (nums[i] != nums[i - 2]) {
36+
a.add(nums[i]);
37+
}
38+
}
39+
40+
counter = a.size();
41+
for (int i = 0; i < counter; i++) {
42+
nums[i] = a.get(i);
43+
}
44+
45+
return counter;
46+
}
47+
48+
}

0 commit comments

Comments
 (0)