Given sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.
Example 1:
Input: arr= [1,1,2]
Output: arr = [1,2]
Approach 1:
Java
public class RemoveDuplicatesArray {public static void main(String[] args) {int arr[] = { 1, 1, 2 };int index = removeDuplicates(arr);for (int i = 0; i < index; i++) {System.out.print(" " + arr[i]);}}public static int removeDuplicates(int[] nums) {if (nums.length <= 1)return nums.length;int curVal = nums[0], index = 1;for (int i = 1; i < nums.length; i++) {if (curVal != nums[i]) {nums[index] = nums[i];index += 1;}curVal = nums[i];}return index;}}// Time Complexity : O(n)// Space Complexity: O(1)
C++
#include <bits/stdc++.h>using namespace std;//Funcion to reomove duplicates//from sorted arrayint removeDuplicates(int arr[],int n){int l=1;int i=1;if(n==0)return 0;while(i<n){if(arr[i]!=arr[i-1])arr[l++]=arr[i];i++;}return l;}int main(){int arr[]={1,1,2};int n=sizeof(arr)/sizeof(arr[0]);n=removeDuplicates(arr,n);for(int i=0;i<n;i++)cout<<arr[i]<<" ";return 0;}//Time Complexity: O(n)//Space Complexity:O(1)
No comments:
Post a Comment