Untitled
unknown
plain_text
2 months ago
1.2 kB
4
Indexable
public class RemoveDuplicates { public static int removeDuplicates(int[] nums) { int n = nums.length; if (n <= 2) return n; // If size is <= 2, return as is. int j = 1; // Pointer for the valid position int count = 1; // Count occurrences of the current number for (int i = 1; i < n; i++) { if (nums[i] == nums[i - 1]) { count++; // Increment count if same as previous } else { count = 1; // Reset count for a new number } if (count <= 2) { // Allow the number only if it appears <= 2 times nums[j] = nums[i]; j++; } } return j; // `j` is the new length of the modified array } public static void main(String[] args) { int[] nums = {0,0,1,1,1,1,2,3,3}; int k = removeDuplicates(nums); // Printing the result System.out.println("Output Length: " + k); System.out.print("Modified Array: "); for (int i = 0; i < k; i++) { System.out.print(nums[i] + " "); } } }
Editor is loading...
Leave a Comment