Reputation: 21
I am trying to solve a problem from Leetcode and could not figure out how to solve it. I looked up the solution but I cannot understand how switching the element can change the array.
"Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns 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."
The question was about removing the duplicate elements and I have to modify the array that was passed as the parameter which means I cannot create a new object.
public int removeDuplicates(int[] nums) {
if (nums.length == 0) return 0;
int i = 0;
for (int j = 1; j < nums.length; j++) {
if (nums[j] != nums[i]) {
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
This is what the solution said and I cannot understand how nums[i] = nums[j] can reduce the size of an array.
Upvotes: 1
Views: 61
Reputation: 18245
You have correct solution. The client code could look like this:
int[] nums = { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4 };
int length = removeDuplicates(nums);
// nums = { 1, 2, 3, 4, 3, 3, 4, 4, 4, 4 } <- look! we have lost 2 and have five 4!
System.out.println("Actual length of array: " + nums.length); // 10
System.out.println("Total unique numbers: " + length); // 4
System.out.print("Unique numbers:");
for (int i = 0; i < length; i++)
System.out.print(" " + nums[i]);
System.out.println();
System.out.print("The rest of array: ");
for (int i = length; i < nums.length; i++)
System.out.print(" " + nums[i]);
As you can see, the array is the same and you cannot change the size of it. But you can move all unique elements to the beginning of the array and retrieve new length to the client (i.e. only firsts length
elements ara correct and do not care about others, they could be any).
Demo:
Actual length of array: 10
Total unique numbers: 4
Unique numbers: 1 2 3 4
The rest of array: 3 3 4 4 4 4
P.S. How do you think ArrayList
actually works?
public class ArrayList<E> {
Object[] elementData;
int size;
}
Upvotes: 1