我試圖來解決CodeFights稱爲firstDuplicate
一個問題,即國家 -查找第一個與複製第二最低的出現指數元素
給定一個數組,其中包含的範圍只有數從1到 一個.length,找到第二個 事件具有最小索引的第一個重複號碼。換句話說,如果有更多的 比1個重複的號碼,返回第二個 發生的索引小於其他 號碼的第二個發生的號碼。如果沒有這樣的元素,則返回-1。
例
對於= [2,3,3,1,5,2],輸出應該是firstDuplicate(A)= 3.
有2次重複:數字2和3.第二次出現3 的索引小於第二次出現的2,因此 的答案爲3.
對於a = [2,3,4,5,1],輸出應該是firstDuplicate(a)= -1。
我的解決方案 -
public class FirstDuplicate {
private static HashMap<Integer, Integer> counts = new HashMap<>();
private static void findSecondIndexFrom(int[] num, int n, int i) {
// given an array, a starting index and a number, find second occurrence of that number beginning from next index
for(int x = i; x < num.length; x++) {
if(num[x] == n) {
// second occurrence found - place in map and terminate
counts.put(n, x);
return;
}
}
}
private static int firstDuplicate(int[] a) {
// for each element in loop, if it's not already in hashmap
// find it's second occurrence in array and place number and index in map
for(int i = 0; i < a.length; i++) {
if(!counts.containsKey(a[i])) {
findSecondIndexFrom(a, a[i], i+1);
}
}
System.out.println(counts);
// if map is empty - no duplicate elements, return -1
if(counts.size() == 0) {
return -1;
}
// else - get array of values from map, sort it, find lowest value and return corresponding key
ArrayList<Integer> values = new ArrayList<>(counts.values());
Collections.sort(values);
int lowest = values.get(0);
//System.out.println(lowest);
for(Map.Entry<Integer, Integer> entries: counts.entrySet()) {
if(entries.getValue() == lowest) {
return entries.getKey();
}
}
return -1;
}
public static void main(String[] args) {
// int[] a = new int[]{2, 3, 3, 1, 5, 2};
//int[] a = new int[]{2, 4, 3, 5, 1};
//int[] a = new int[]{8, 4, 6, 2, 6, 4, 7, 9, 5, 8};
//int[] a = new int[]{1, 1, 2, 2, 1};
int[] a = new int[]{10, 6, 8, 4, 9, 1, 7, 2, 5, 3};
System.out.println(firstDuplicate(a));
}
}
此解決方案僅用於傳遞對CodeFights 11測試用例約4。但是,我手動執行了我的IDE中的每個測試用例,並且每個測試用例都產生了正確的結果。
我不明白爲什麼這不會在CodeFights中工作。它是否與使用靜態HashMap
有關?
可能,嘗試添加一個'counts.clear()'來firstDuplicate的'開頭()'... –
的怎麼辦這個問題,而無需使用額外的空間,任何想法(MAPS這裏) –
爲什麼我們是否需要一張地圖?,它足以跟蹤最小索引 – hunter