LeetCode – Remove Duplicates from Sorted Array (Java)
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 should return length = 2, and A is now [1,2].
Analysis
The problem is pretty straightforward. It returns the length of the array with unique elements, but the original array need to be changed also. This problem is similar to Remove Duplicates from Sorted Array II.
Java Solution
public static int removeDuplicates(int[] A) { if (A.length < 2) return A.length; int j = 0; int i = 1; while (i < A.length) { if (A[i] != A[j]) { j++; A[j] = A[i]; } i++; } return j + 1; } |
Note that we only care about the first unique part of the original array. So it is ok if input array is {1, 2, 2, 3, 3}, the array is changed to {1, 2, 3, 3, 3}.
<pre><code> String foo = "bar"; </code></pre>
-
Alik Elzin
-
Amr Hendy
-
Prashi Dell
-
ryanlr
-
Saeed W Aghaee
-
Saeed W Aghaee
-
Milos Kosanovic
-
Milos Kosanovic
-
Nimish Unde
-
Kshama Dalal
-
Peeyush Chandel
-
orkhan huseynli
-
Avinash Ujjwal
-
Thierry E N
-
Arafath Ali
-
Dileep Buddaraju
-
Gokhan
-
Taoufik Bdiri
-
Ken
-
jitendra varshney from K.I.E.T
-
jitendra varshney from K.I.E.T
-
sola
-
Guilherme Santos
-
Neel Sheyal
-
dm
-
sireen
-
Vivek Venkatesh
-
Neel Sheyal
-
ryanlr
-
Matt Auerbach
-
ryanlr
-
Matt Auerbach