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 firstk
elements ofnums
contain the unique elements in the order they were present innums
initially. The remaining elements ofnums
are not important as well as the size ofnums
. - Return
k
.
class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length==0)
return 0;
if(nums.length==1)
return 1;
int itter = 0;int k = 0;
for(int i = 1;i<nums.length;i++){
if(i==nums.length-1){
int res = nums[i]^nums[itter];
if(res==0){
nums[i] = Integer.MAX_VALUE;
}
itter++;
i = itter+1;
if(itter==nums.length-1)
break;
if(nums[itter]==Integer.MAX_VALUE){
itter++;
i = itter+1;
if(itter==nums.length-1)
break;
}
}
int res = nums[i]^nums[itter];
if(res==0){
nums[i] = Integer.MAX_VALUE;
}
}
int []tmp = new int[nums.length];
int j = 0;
for(int i = 0;i<nums.length;i++){
if(nums[i]!=Integer.MAX_VALUE)
tmp[j++] = nums[i];
}
int size = 0;
for(int i = 0;i<j;i++){
nums[i] = tmp[i];
size++;
}
return size;
}
}