我试图来解决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