In: Computer Science
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,1,2,2,3], Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,0,1,1,1,1,2,3,3], Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively. It doesn't matter what values are set beyond the returned length.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
CODE::
import java.util.Scanner;
class Main {
public static int removeDuplicates(int[] nums){
// your code goes here
if(nums.length == 0) return 0;
if(nums.length == 1) return 1;
if(nums.length == 2) return 2;
int index = 0;
if(nums.length > 2){
for(int i = 0; i < nums.length - 2; i++){
if(nums[i] != nums[i+1]){
nums[index] = nums[i];
index++;
} else{
if(nums[i+1] != nums[i+2]){
nums[index] = nums[i];
index++;
}
}
}
if(index <= nums.length - 2){
nums[index] = nums[nums.length - 2];
index++;
nums[index] = nums[nums.length - 1];
}
return index + 1;
}else
return -1;
}
public static void main(String[] args) {
// take array input here
int[] nums = new int[]{1, 1, 1, 2, 2, 3};
// output goes here
int newLength = removeDuplicates(nums);
if(newLength <= 0){
System.out.println("Array is empty");
}
else{
for(int i = 0; i < newLength; i++){
System.out.plint(nums[i] + " ");
}
System.out.println();
}
}
}
Program ScreenShot :
Program code:
import java.util.Scanner;
class Main {
public static int removeDuplicates(int[] nums) {
// your code goes here
if (nums.length == 0)
return 0;
if (nums.length == 1)
return 1;
if (nums.length == 2)
return 2;
int index = 0;
if (nums.length > 2) {
for (int i = 0;
i < nums.length - 2; i++) {
if (nums[i] != nums[i + 1]) {
nums[index] = nums[i];
index++;
} else {
if (nums[i + 1] != nums[i +
2]) {
nums[index] = nums[i];
index++;
}
}
}
if (index
<= nums.length - 2) {
nums[index] = nums[nums.length - 2];
index++;
nums[index] = nums[nums.length - 1];
}
return index +
1;
} else
return -1;
}
public static void main(String[] args) {
// take array input here
int[] nums = new int[] { 1, 1, 1,
2, 2, 3 };
// output goes here
int newLength =
removeDuplicates(nums);
System.out.println("length = " +
newLength);
System.out.print("The first " +
newLength + " of nums is : ");
if (newLength <= 0) {
System.out.println("Array is empty");
} else {
for (int i = 0;
i < newLength; i++) {
System.out.print(nums[i]);
if(i < newLength -1)
System.out.print(",");
}
}
}
}
Sample Output :