Remove Duplicates from Sorted Array

Problem: 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. Consider the number of unique elements in nums to be k. After removing duplicates, return the number of unique elements k. The first k elements of nums should contain the unique numbers in sorted order. The remaining elements beyond index k - 1 can be ignored. Idea: Given that array is sorted in increasing order and to main the relative order of array, All we need to do is that take two pointers adjacent pointer at start where compare left to right using second pointer with first pointer and check if elements at first and second aren't same, then increase first pointer and replace element of 1st pointer with second pointer and return first +1; class Main {   public static void main(String[] args) {     System.out.println("Try programiz.pro");     int[] nums={0,0,1,2,3,3,3,3,5,6};     int unqiueCount = removeDuplicates(nums);     System.out.println("Total unqiue element after removing duplicates are: "+ unqiueCount);   }       static int removeDuplicates(int[] nums) {      int first = 0;     for(int second = 1; second<nums.length; second ++){       if(nums[first]!=nums[second]){       first++;       nums[first]=nums[second];       }     }     return first+1;   } } #java8 #corejava #programming #practice #java #code #leetcodeproblem #problemsolving

  • icon

To view or add a comment, sign in

Explore content categories