LeetCode – Remove Duplicates from Sorted Array II (Java)
Follow up for "Remove Duplicates": What if duplicates are allowed at most twice?
For example, given sorted array A = [1,1,1,2,2,3], your function should return length = 5, and A is now [1,1,2,2,3].
So this problem also requires in-place array manipulation.
Java Solution 1
We can not change the given array's size, so we only change the first k elements of the array which has duplicates removed.
public int removeDuplicates(int[] nums) { if(nums==null){ return 0; } if(nums.length<3){ return nums.length; } int i=0; int j=1; /* i, j 1 1 1 2 2 3 step1 0 1 i j step2 1 2 i j step3 1 3 i j step4 2 4 i j */ while(j<nums.length){ if(nums[j]==nums[i]){ if(i==0){ i++; j++; }else if(nums[i]==nums[i-1]){ j++; }else{ i++; nums[i]=nums[j]; j++; } }else{ i++; nums[i]=nums[j]; j++; } } return i+1; } |
The problem with this solution is that there are 4 cases to handle. If we shift our two points to right by 1 element, the solution can be simplified as the Solution 2.
Java Solution 2
public int removeDuplicates(int[] nums) { if(nums==null){ return 0; } if (nums.length <= 2){ return nums.length; } /* 1,1,1,2,2,3 i j */ int i = 1; // point to previous int j = 2; // point to current while (j < nums.length) { if (nums[j] == nums[i] && nums[j] == nums[i - 1]) { j++; } else { i++; nums[i] = nums[j]; j++; } } return i + 1; } |
<pre><code> String foo = "bar"; </code></pre>
-
Alik Elzin
-
Amr Hendy
-
xpress razor
-
RaveeendraGuntupalli
-
Somya Kajla
-
Ankit Shah
-
Larry Okeke
-
Swathi
-
cp
-
vincent
-
Liang Tao
-
TK
-
claire
-
Walter
-
W Han