我試圖解決hackerrank中的一個問題,該問題是查找數組中具有最大度數的最小子陣列的長度。數組的最大度數是具有最大頻率的元素的數量。例如,考慮例子{2,2,1,2,3,1,1}最小子數組長度爲4,因爲2具有最大度數,並且具有度數3的最小子數組是{2,2, 1,2}查找陣列中具有最大度數的最小子陣列的長度
下面是我的問題
public class FindingMinSubArrayWithDegree {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
System.out.println(degreeOfArray(arr));
sc.close();
}
static int degreeOfArray(int[] arr) {
HashMap<Integer, Integer> numbersByDegree = new HashMap<Integer, Integer>();
for (int i = 0; i < arr.length; i++) {
int degree = numbersByDegree.getOrDefault(arr[i], 0);
numbersByDegree.put(arr[i], degree + 1);
}
List<Map.Entry<Integer, Integer>> sortedEntries = sortByValue(numbersByDegree);
int maxDegree = sortedEntries.get(0).getValue();
int[] degreeArr = new int[arr.length] ;
int minSubArrayLength = arr.length;
for (Map.Entry<Integer, Integer> entry : sortedEntries) {
if (entry.getValue() < maxDegree) {
break;
}
boolean startIndexFound = false, endIndexFound = false;
int startIndex = 0, endIndex = 0;
for (int i = 0; i < arr.length; i++) {
if (entry.getKey() == arr[i]) {
if (i - 1 >= 0)
degreeArr[i] = degreeArr[i - 1] + 1;
else
degreeArr[i] = 1;
} else {
if (i - 1 >= 0)
degreeArr[i] = degreeArr[i - 1];
}
if (!startIndexFound && degreeArr[i] == 1) {
startIndex = i;
startIndexFound = true;
}
if (!endIndexFound && degreeArr[i] == entry.getValue()) {
endIndex = i;
endIndexFound = true;
}
if (startIndexFound && endIndexFound)
break;
}
startIndexFound = false; endIndexFound = false;
if ((endIndex - startIndex) < minSubArrayLength) {
minSubArrayLength = endIndex - startIndex;
}
for (int i = 0; i < degreeArr.length; i++)
degreeArr[i] = 0;
}
return minSubArrayLength + 1;
}
private static <K, V extends Comparable<? super V>> List<Map.Entry<K, V>>
sortByValue(Map<K, V> map) {
List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
return (o2.getValue()).compareTo(o1.getValue());
}
});
return list;
}
}
這種方法具有運行的O時的最壞情況的解決方案(N^2),用於像{1,1,2,2,3的輸入,3,4,4}。這個問題有更好的算法嗎?
PS - 我試着問在代碼審查這個問題,但沒有得到,這就是爲什麼搬到這裏
什麼是'degree'陣列的? –
數組的度數是具有最大頻率的元素的數量 –