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 innums.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Note that even though we want you to return the new length, make sure to change the original array as well in place.
Input: nums =[1,1,2]Output: 2, nums =[1,2,_]Explanation: Your function should return k =2,with the first two elements of nums being 1 and 2 respectively.It does not matter what you leave beyond the returned k(hence they are underscores).
Example 2:
1
2
3
4
Input: nums =[0,0,1,1,1,2,2,3,3,4]Output: 5, nums =[0,1,2,3,4,_,_,_,_,_]Explanation: Your function should return k =5,with the first five elements of nums being 0,1,2,3, and 4 respectively.It does not matter what you leave beyond the returned k(hence they are underscores).
The problem is pretty straightforward. It returns the length of array with unique elements, but the original array need to be changed also. This problem should be reviewed with Remove duplicates from Sorted Array 2
This method returns the number of unique elements, but does not change the original array correctly. For example, if the input array is {1, 2, 2, 3, 3}, the array will be changed to {1, 2, 3, 3, 3}. The correct result should be {1, 2, 3}. So, we return left pointer.
If we only want to count the number of unique elements, the following method is good enough.
1
2
3
4
5
6
7
8
9
10
// Count the number of unique elementspublicstaticintcountUnique(int[] A) {
int count = 0;
for (int i = 0; i < A.length- 1; i++) {
if (A[i]== A[i + 1]) {
count++;
}
}
return (A.length- count);
}