Skip to content

Instantly share code, notes, and snippets.

@tiagopereira17
Created July 6, 2016 15:44
Show Gist options
  • Save tiagopereira17/a29ee4965a391bd55b8a1fa44327b1ae to your computer and use it in GitHub Desktop.
Save tiagopereira17/a29ee4965a391bd55b8a1fa44327b1ae to your computer and use it in GitHub Desktop.
Compute number of distinct values in an array.
import java.util.Arrays;
public class Distinct {
public int distinctElements(int[] A) {
if(A == null || A.length == 0) {
return 0;
}
Arrays.sort(A);
int counter = 1;
for(int i = 1; i < A.length; i++) {
if(A[i] != A[i - 1]) {
counter++;
}
}
return counter;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment