I would like to understand a specific line in this code I am studying from geeksfogeeks. Here is the main code:
class Main
{
// Function to remove duplicate elements
// This function returns new size of modified
// array.
static int removeDuplicates(int arr[], int n)
{
// Return, if array is empty
// or contains a single element
if (n==0 || n==1)
return n;
int[] temp = new int[n];
// Start traversing elements
int j = 0;
for (int i=0; i<n-1; i++)
// If current element is not equal
// to next element then store that
// current element
if (arr[i] != arr[i+1])
temp[j++] = arr[i];
// Store the last element as whether
// it is unique or repeated, it hasn't
// stored previously
temp[j++] = arr[n-1];
// Modify original array
for (int i=0; i<j; i++)
arr[i] = temp[i];
return j;
}
public static void main (String[] args)
{
int arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5};
int n = arr.length;
n = removeDuplicates(arr, n);
// Print updated array
for (int i=0; i<n; i++)
System.out.print(arr[i]+" ");
}
}
If I understand this code correctly, what it is doing is iterating through the intial given array and comparing if the next element of the array is of same value. If it's not, then it adds that 'unique' element to the temp array, which then uses the value of j (which has been increasing in value according to how many unique elements there are) to rewrite the original array over.
What I don't get is this line
temp[j++] = arr[n-1];
What is the purpose of this line? I know it is increasing the value of J but the " n-1" doesn't make whole lot of sense.
I would appreciate any insight on this topic and thank you ahead of time for well..your time.