Remove Duplicates from Sorted Array -- Remove duplicate elements from the sorting Array
Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array A =[1,1,2]
,
Your function shocould return length =2
, And A is now[1,2]
.
Ideas:
(1) This question is actually very simple. This is mainly because the array is already sorted in order. If you do not carefully read the question and operate the array as an unordered array, OJ will display a timeout.
(2) The question requirement is that you cannot apply for two additional spaces. If you submit an application for additional space, the application fails.
(3) Note that the element position in the array cannot be changed. For example, for an array [, 5], after the repeated elements are removed, the value is [, 5], and the starting number is 1, instead of other numbers.
(4) We only need to traverse the Group once and set a counter. Each time the elements before and after traversal are different, the counter is incremented by 1, and positions the counter in the array to the element currently traversed.
The algorithm code is implemented as follows:
public static int removeDuplicates(int[] A) {int len = A.length;if (len == 0)return 0;int count = 1;for (int i = 1; i < len; i++) {if (A[i] == A[i - 1]) {continue;}else{A[count] = A[i];count++;}}return count;}
The above solution is for ordered arrays. What should I do if it is an unordered array?
Ideas:
(1) If you are not allowed to apply for additional space, you can sort the array first. To improve the efficiency, you can use quick sorting and then operate it by referring to the ordered array above;
(2) If space application is allowed, you only need to create a HashSet, traverse the array once, and use the contanins () method to determine the result.
(1) and (2) the corresponding code is as follows (NOTE: For the questions shown in this article, if the following code is used for OJ, (1) Will time out, (2) will generate additional space ):
You cannot apply for additional space:
Public static int removeDuplicates (int [] A) {int len =. length; if (len = 0) return 0; quickSort (A, 0, len-1); int count = 1; for (int I = 1; I <len; I ++) {if (A [I] = A [I-1]) {continue;} else {A [count] = A [I]; count ++ ;}} return count ;}// fast sort private static void quickSort (int [] table, int low, int high) {if (low
You can apply for additional space: (The contains () method of HashSet is used to filter duplicate elements)
public static int removeDuplicates(int[] A) {int len = A.length;HashSet
set = new HashSet
();for (int i = 0; i < len; i++) {if (set.size() == 0) {set.add(A[i]);}if (!set.contains(A[i])) {set.add(A[i]);}}return set.size();}