2017-02-27 58 views
0
public static int[] isthereDuplicates(int[] combination) { 
    Set<Integer> foundedNumbers = new HashSet<>(); 

    for (int i= 0; index < combination.length; i++) { 
     if (foundedNumbers.contains(combination[i])) { 
       combination[i] -= 1; 
     } else { 
      foundedNumbers.add(combination[i]); 
     } 

    return combination; 
} 

我需要查找并替换数组数组中的重复项。数组数组也是随机选择1到40之间的7个数字。如果我有一个副本,但是当我有几个例如我有1,14,20,1,38,1,5时,我提出的代码是有效的。它会改变为中间1,但第二个1将保持不变。java阵列查找重复项并替换它们

+1

为什么你定义一个HashSet的则从来没有使用它? ('nadjeniBrojevi') –

+0

当您将变量名称翻译成英文(为什么首先不是英文?),那么请翻译所有变量名称。你的param和Set仍然需要翻译。 – Tom

+1

您可以告诉我们您发布的输入(1,14,20,1,38,1,5),您要查找的结果是什么? –

回答

0

你的代码似乎有小的修改和翻译位工作。

public static int[] imaliDuplikata(int[] combination) { 
    Random r = new Random(); 
    Set<Integer> foundeNumbers = new HashSet<>(); 

    for (int i = 0; i < combination.length; i++) { 
     if (foundeNumbers.contains(combination[i])) { 
      combination[i] = r.nextInt(40); 
     } else { 
      foundeNumbers.add(combination[i]); 
     } 

    } 
    return combination; 
} 

执行。在这种方式:

int[] i = {1,14,20,1,38,1,5}; 
System.out.println(Arrays.toString(imaliDuplikata(i))); 

你会得到所有出现反复更换号码。

各种执行:

[1, 14, 20, 0, 38, 35, 5] 
[1, 14, 20, 11, 38, 1, 5] 
[1, 14, 20, 22, 38, 30, 5] 
[1, 14, 20, 37, 38, 39, 5] 
+2

它可以返回重复值,即:'[1,14,20,38,38,39,5]'' r.nextInt(40);'可以返回相同数量的所有的时间 – Uata

+0

霍尔迪阿,我beleive那它的工作,因为我尝试了10次,我从来没有重复。但我会尝试挖掘一些其他解决方案,以确保它始终可以。 – Mapet

+0

Matil @Uata说的是正确的,你可以重复使用这个解决方案,因为你得到一个随机数,但你可以添加一段时间来检查随机int是否已经在Map中,而不是添加它,否则,获得一个新的随机值。 .. –

0

我相信这能解决你的问题:

首先你确定你的数组中的号码和你记录他们没有被发现呢。

然后你去的数字,当你找到一个还没有被发现,你把它标记为找到。

当你找到任何你想用它做你做得再数(在这种情况下,我把它的值-1)

public static int[] duplicates(int[] combination) { 
      HashMap<Integer, Boolean> foundNumbers = new HashMap<>(); 
      for (int i : combination) { 
       if(foundNumbers.containsKey(i)) continue; 
       foundNumbers.put(i, false); 
      } 

      for (int i = 0; i < combination.length; i++) { 
       if(!foundNumbers.get(combination[i])) { 
        foundNumbers.put(combination[i], true); 
       } else { 
        combination[i] = -1; 
       } 
      } 

      return combination; 
     } 
+0

阿诺我也试过你的代码,因为我了解你的步骤,但它不断做出重复。谢谢无论如何。 – Mapet