Reputation: 219
function countUniqueValues(arr){
if(arr.length === 0) return 0;
var i = 0;
for(var j = 1; j < arr.length; j++){
if(arr[i] !== arr[j]){
i++;
arr[i] = arr[j]
}
}
return i + 1;
}
countUniqueValues([1,2,2,5,7,7,99])
I am studying algorithm using Javascript. The question is as follows : Implement a function called countUniqueValues, which accepts a sorted array, and count the unique values in the array. There can be negative numbers in the array, but it will always be sorted.
The above is the answer in the lecture, but I am having trouble understanding why you need
arr[i] = arr[j]
as you just need the value of i to increase to see the number of unique values using the array index. Can anyone explain me why we need
arr[i] = arr[j]
Upvotes: 0
Views: 103
Reputation: 27
arr[i] = arr[j]
This means exactly this. If two array elements are equal, they must be counted as one. Hence, it singles out the two array elements. Update array when there is no equality.
Lets write step by step.
i=0
j=1
Loop 1:
arr[i=0](1) !== arr[j=1](2)
i+1(i=1)
arr[1]=arr[1](2)
Loop 1 Result:
i=1 arr[1]=2
Old Array:([1,2,2,5,7,7,99])
New Array:([1,2,2,5,7,7,99])
Loop 2:
arr[i=1](2) == arr[j=2](2)
//Do Nothing
Loop 2 Result:
i=1 arr[1]=2
Loop 3:
arr[i=1](2) !== arr[j=3](5)
i+1(i=2)
arr[2]=arr[3](5)
Loop 3 Result:
i=2 arr[2]=5
Old Array:([1,2,2,5,7,7,99])
New Array:([1,2,5,5,7,7,99])
Loop 4:
arr[i=2](5) !== arr[j=4](7)
i+1(i=3)
j+1(j=5)
arr[3]=arr[4](7)
Loop 4 Result:
i=3 arr[3]=7
Old Array:([1,2,5,5,7,7,99])
New Array:([1,2,5,7,7,7,99])
Loop 5:
arr[i=3](7) == arr[j=5](7)
j+1
//Do Nothing
Loop 5 Result:
i=3 j=6
Loop 6:
arr[i=3](7) !== arr[j=6](99)
i+1(i=4)
j+1(j=7)
arr[4]=arr[6](99)
Loop 6 Result:
i=4 arr[4]=99
Old Array:([1,2,5,7,7,7,99])
New Array:([1,2,5,7,99,7,99])
. . . .
FINAL
i=4
Last Array:([1,2,5,7,99])
You can reach the result with arr[].length
OR i+1
(add the index [0] for the array)
Upvotes: 1