Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once
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.
Solution :
[class Solution {
public int removeDuplicates(int[] nums) {
LinkedHashMap<Integer, Integer> linkedMap = new LinkedHashMap<>();
for (int i = 0; i < nums.length; i++){
linkedMap.put(nums[i], i);
}
int size = linkedMap.size();
int i = 0;
for (int j : linkedMap.keySet()){
nums[i] = j;
i++;
}
return size;
}
}]
Explanation :
In this question, all you have to do is remove the duplicates from that array. So we use hashmap for this solution with O ( N ) time complexity.
Also, the relative order of elements should be the same. So using Linked HashMap we will be able to keep the given order same.
Declare a linked hashmap and put all the elements into the linked hashmap where the key of the hashmap is the element in the array and the value is the index.
The duplicates have already been removed. All you have to do is put all elements in the hashmap back into the array using a for loop and return the array.
COMMENTS