-1

I need to print [1,2,3,4] when I get array like [1,1,2,2,3,3,4].

Other examples:

input=[1,1,1,2] output should be=[1,2]

input=[1,1,1,1] output should be=[1]

 int count=1;
 //This for counts only the different numbers of the array input.
 for(int i=0; i<array.length-1;i++){
            if(array[i+1]!=array[i]){
                count++;

            }
        }
        //New array only for the needed numbers.
        Integer [] res = new Integer[count];
        res[0] = array[0];
        for(int i = 1;i<count;i++){
            if(array[i]!=array[i+1]){
                res[i]=array[i+1];
            }
        }

With input [1,1,2,2,3,3,4] I get [1, 2, null, 3].

Should be [1,2,3,4].

naikon28
  • 13
  • 2

1 Answers1

1

One problem is that you increment the loop's counter even when array[i]==array[i+1], which results in the output array having null values.

Another problem is that you don't iterate over all the elements of the input array in the second loop.

Both problems can be solved if you use two indices, one for the input array (the loop's variable) and another for the current position in the output array :

int count=1;
for(int i=0; i<array.length-1;i++){
    if(array[i+1]!=array[i]){
        count++;
    }
}
Integer [] res = new Integer[count];
res[0] = array[0];
int resIndex = 1;
for(int i = 1; i < array.length - 1; i++){
    if(array[i] != array[i+1]) {
        res[resIndex] = array[i+1];
        resIndex++;
    }
}

EDIT :

As fabian suggested, changing the second loop to

for(int i = 1 ; i < array.length - 1 && resIndex < count; i++)

can make it slightly faster if the last unique number of the input array repeats multiple times.

Eran
  • 387,369
  • 54
  • 702
  • 768