Remove the duplicate number from Array keep twice a number.
Example 1:
Input: arr[]={1, 4, 5, 5, 6, 7, 7, 7, 9} Output: arr[]={1, 4, 5, 5, 6, 7,7,9}
Approach 1:
Java
public class RemoveDuplicatesArrayII {public static void main(String[] args) {int arr[] = { 1, 4, 5, 5, 6, 7, 7, 7, 9 };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 <= 2)return nums.length;int prev = 0, count = 0, len = 1;for (int i = 1; i < nums.length; i++) {if (nums[prev] < nums[i]) {count = 0;nums[len] = nums[i];len = len + 1;} else if ((nums[prev] == nums[i]) && count == 0) {count++;nums[len] = nums[i];len = len + 1;}prev = i;}return len;}}//Time Complexity: O(n)//Space Complexity: O(1)
C++
#include <bits/stdc++.h>using namespace std;int removeDuplicates(int nums[],int n){int l=0;int i=0;while(i<n){int cnt=1;nums[l++]=nums[i];i++;while(i<n&&nums[i]==nums[i-1]){cnt++;if(cnt<3)nums[l++]=nums[i];i++;}}return l;}int main(){int nums[] = { 1, 4, 5, 5, 6, 7, 7, 7, 9 };int n=sizeof(nums)/sizeof(nums[0]);n = removeDuplicates(nums,n);for (int i = 0; i < n; i++)cout<<nums[i]<<" ";return 0;}// Time Complexity: O(n)// Space Complexity: O(1)
No comments:
Post a Comment