Remove Duplicates from Sorted Array LeetCode Solution

Here, We see Remove Duplicates from Sorted Array problem Solution. This Leetcode problem done in many programming language like C++, Java, JavaScript, Python etc.

Remove Duplicates from Sorted Array

Remove Duplicates from Sorted Array

Problem Statement ->

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.

Example 1:
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]

Example 2:
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]

Remove Duplicates from Sorted Array C++ Solution ->

class Solution { public: int removeDuplicates(vector<int>& nums) { nums.erase(std::unique(nums.begin(), nums.end()), nums.end()); return nums.size(); } };
Code language: C++ (cpp)

Remove Duplicates from Sorted Array Java Solution->

class Solution { public int removeDuplicates(int[] nums) { if (nums.length == 0) return 0; int i = 0; for (int j = 1; j < nums.length; j++) { if (nums[j] != nums[i]) { i++; nums[i] = nums[j]; } } return i + 1; } }
Code language: Java (java)

Remove Duplicates from Sorted Array JavaScript Solution ->

var removeDuplicates = function(nums) { let c=1 for(let i=1;i<nums.length;i++){ if(nums[i]==nums[i-1])continue nums[c]=nums[i] c++ } let l=nums.length-1 while(l>=c){ nums.pop() l-- } };
Code language: JavaScript (javascript)

Remove Duplicates from Sorted Array Python Solution ->

class Solution: def removeDuplicates(self, nums): len_ = 1 if len(nums)==0: return 0 for i in range(1,len(nums)): if nums[i] != nums[i-1]: nums[len_] = nums[i] len_ +=1 return len_
Code language: Python (python)

Leave a Comment

Your email address will not be published. Required fields are marked *