简体   繁体   English

在数组中查找重复值

[英]Finding repeating values in array

I have an array with 4 integers and I need to find if there any repeating values and what are those repeating values.我有一个包含 4 个整数的数组,我需要查找是否有任何重复值以及那些重复值是什么。 I have tried to use nested loops but it counts each integer in array twice:我曾尝试使用嵌套循环,但它对数组中的每个整数计数两次:

for (int f = 0; f < bonusGame.length; ++f) {
    for (int j = 0; j < bonusGame.length; ++j) {
        if (f == j & f == 10) {
            System.out.println("You won 10 Euro");
        }
    }
}
for (int i= array.lenght;i >0;i--){
      if (array[i]==array[i-1]){
         system.out.print("you won ")
}
 }

// i think it will work // 我认为它会起作用

You should take a look at HashSet .你应该看看HashSet This way you can create a O(n) algorithm, but you have to use Integer instead of int, which can be a problem in some case :这样你就可以创建一个 O(n) 算法,但你必须使用整数而不是整数,这在某些情况下可能是一个问题:

for (int num : bonusGame) {
     if (!hashSet.add(num) ) { // unauto-boxing
        // num is duplicate
     }

Or, you can call Arrays.sort(bonusGame) and compare the elements with only one loop :或者,您可以调用Arrays.sort(bonusGame)并仅使用一个循环比较元素:

Arrays.sort(bonusGame);
for(int i=0 ; i<bonusGame.length - 1; i++) {
    if(bonusGame[i] == bonusGame[i+1]) {
         // bonusGame[i] is duplicate
    }
}

something like this像这样的东西

for (int f = 0; f < bonusGame.length - 1; ++f) {
    for (int j = f + 1; j < bonusGame.length; ++j) {
        if (bonusGame[f] == bonusGame[j]) {
            System.out.println("Duplicate " + bonusGame[f]);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM