Description
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.
Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:
Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
Return k.
Custom Judge:
The judge will test your solution with the following code:
1int[] nums = [...]; // Input array
2int[] expectedNums = [...]; // The expected answer with correct length
3
4int k = removeDuplicates(nums); // Calls your implementation
5
6assert k == expectedNums.length;
7for (int i = 0; i < k; i++) {
8 assert nums[i] == expectedNums[i];
9}
If all assertions pass, then your solution will be accepted.
Example 1:
1Input: nums = [1,1,2]
2Output: 2, nums = [1,2,_]
3Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
4It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:
1Input: nums = [0,0,1,1,1,2,2,3,3,4]
2Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
3Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
4It does not matter what you leave beyond the returned k (hence they are underscores).
Constraints:
1 <= nums.length <= 3 * 10^4-100 <= nums[i] <= 100numsis sorted in non-decreasing order.
Solution
This could be solved using two pointers or sliding window. We will have two pointers starting with two adjacent positions. As long as they are same, we keep increasing the window size. When they both are not equal, we just swap the two numbers in the array.
1class Solution {
2 public int removeDuplicates(int[] nums) {
3 int left = 0, right = 1;
4 while (right < nums.length) {
5 if (nums[left] == nums[right]) {
6 right++;
7 } else {
8 left++;
9 nums[left] = nums[right];
10 }
11 }
12 return left + 1;
13 }
14}
Alternative solution would be to simply iterate through all elements. In this case, we have to keep track of count variable which will also help in swapping unique numbers. In this we compare using single index i and in each iteration compare i with i-1 value from nums array.
1class Solution {
2 public int removeDuplicates(int[] nums) {
3 int count = 0;
4 for (int i = 1; i < nums.length; i++) {
5 if (nums[i] == nums[i - 1])
6 count++;
7 else
8 nums[i - count] = nums[i];
9 }
10 return nums.length - count;
11 }
12}


Comments