Skip to content

Instantly share code, notes, and snippets.

@sgallese
Created April 11, 2018 15:30
Show Gist options
  • Save sgallese/5ccbd1369e9fc880a22a8185c0480b39 to your computer and use it in GitHub Desktop.
Save sgallese/5ccbd1369e9fc880a22a8185c0480b39 to your computer and use it in GitHub Desktop.
static int degreeOfArray(int[] arr) {
int max = 0;
Map<Integer, Integer> map = new HashMap<>();
Map<Integer, Integer> startIndex = new HashMap<>();
Map<Integer, Integer> endIndex = new HashMap<>();
for(int i = 0; i < data.length; i++){
int value = data[i];
if(map.containsKey(value)){
map.put(value, map.get(value) + 1);
}else{
startIndex.put(value, i);
map.put(value, 1);
}
endIndex.put(value, i);
max = Integer.max(max, map.get(value));//Calculate the degree of the array
}
int result = data.length;
for(int i : map.keySet()){
if(map.get(i) == max){
int len = endIndex.get(i) - startIndex.get(i) + 1;
result = Integer.min(result, len);
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment