1+ package com .leetcode .arrays ;
2+
3+ import java .util .Arrays ;
4+
5+ /**
6+ * Level: Easy
7+ * Problem Link: https://leetcode.com/problems/remove-duplicates-from-sorted-array/
8+ * Problem Description:
9+ * Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
10+ * <p>
11+ * Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
12+ * Example 1:
13+ * <p>
14+ * Given nums = [1,1,2]
15+ * <p>
16+ * Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
17+ * <p>
18+ * It doesn't matter what you leave beyond the returned length.
19+ *
20+ * @author rampatra
21+ * @since 2019-04-24
22+ */
23+ public class RemoveDuplicates {
24+
25+ /**
26+ * Time complexity: O(n)
27+ * where,
28+ * n = no. of elements in the array
29+ * <p>
30+ * Runtime: <a href="https://leetcode.com/submissions/detail/224719750/">1 ms</a>.
31+ *
32+ * @param nums
33+ * @return
34+ */
35+ public static int removeDuplicatesInSortedArray (int [] nums ) {
36+ int insertIndex = 0 ;
37+
38+ for (int i = 1 ; i < nums .length ; i ++) {
39+ if (nums [i ] != nums [i - 1 ]) {
40+ nums [++insertIndex ] = nums [i ];
41+ }
42+ }
43+
44+ return insertIndex + 1 ;
45+ }
46+
47+ public static void main (String [] args ) {
48+ int [] arr = new int []{1 , 1 , 2 };
49+ System .out .println (removeDuplicatesInSortedArray (arr ));
50+ System .out .println (Arrays .toString (arr ));
51+
52+ arr = new int []{0 , 0 , 1 , 1 , 1 , 2 , 2 , 3 , 3 , 4 };
53+ System .out .println (removeDuplicatesInSortedArray (arr ));
54+ System .out .println (Arrays .toString (arr ));
55+
56+ arr = new int []{0 , 1 , 2 , 3 , 4 , 5 };
57+ System .out .println (removeDuplicatesInSortedArray (arr ));
58+ System .out .println (Arrays .toString (arr ));
59+ }
60+ }
0 commit comments