-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveDuplicates.java
More file actions
29 lines (25 loc) · 918 Bytes
/
Copy pathRemoveDuplicates.java
File metadata and controls
29 lines (25 loc) · 918 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class RemoveDuplicates {
public int removeDuplicates(int[] nums) {
if (nums.length == 0) {
return 0;
}
int k = 1; // Initialize the count of unique elements to 1
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[k - 1]) {
nums[k] = nums[i]; // Overwrite the next unique element
k++;
}
}
return k;
}
public static void main(String[] args) {
RemoveDuplicates solution = new RemoveDuplicates();
int[] nums = {1, 1, 2, 2, 3}; // Sample input
int length = solution.removeDuplicates(nums);
System.out.println("Length of array after removing duplicates: " + length);
System.out.print("Array after removing duplicates: ");
for (int i = 0; i < length; i++) {
System.out.print(nums[i] + " ");
}
}
}