Nerd For Tech
Published in

Nerd For Tech

Remove Duplicates from Sorted Array — LeetCode

Photo by Roman Synkevych on Unsplash
  • 0 <= nums.length <= 3 * 104
  • -100 <= nums[i] <= 100
  • nums is sorted in non-decreasing order
int[] nums = [...]; // Input array
int[] expectedNums = [...]; // The expected answer with correct length
int k = removeDuplicates(nums); // Calls your implementationassert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums[i] == expectedNums[i];
}

My Solution —

class solution {
public:
int removeDuplicates(vector<int>& nums)//given parameter's vector
{
unordered_set<int> s; // taken a set as a variable
for(int i:nums) // mapped through all the elements of nums
s.insert(i); //inserted the non duplicate elements in s
nums.clear() // emptied the vector nums
for(int i:s)
nums.push_back(i) //appended the elements from s to nums
sort(nums.begin(), nums.end()) //sorted nums
return s.size()
}
}

Runtime: 20 ms

Memory Usage: 18.9 MB

Other Solution —

class Solution { 
public:
int removeDuplicates(vector<int>& nums)
{
int j = 0;
int n = nums.size();
if(n <= 1) return n; //return the size of nums if n<=1
for(int i = 1; i<n; i++)
{
if(nums[i] != nums[j])
{
j++;
nums[j] = nums[i]; //
}
}
return j+1;
}
};

Runtime: 16 ms

Memory Usage: 18.2 MB

--

--

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Arash Arora

Hey! I'm Arash Arora, currently pursuing my Btech in CSE with cybersecurity as a specialization.