简体   繁体   English

在Java数组中查找重复项

[英]Finding duplicates in java Array

Anyway, I have this extremely simple java program to find out if 2 objects in an array are the same. 无论如何,我有这个非常简单的Java程序来找出数组中的2个对象是否相同。 How ever when I run it when a set of unique objects it always returns 1 error, If I add more objects that are the same it counts as normal. 当我运行一组唯一对象时,它总是会返回1个错误,如果我添加更多相同的对象,它将被视为正常。

This is the code; 这是代码;

int[] array= new int[] {1,245,324,523};

    int size = array.length;
    int error=0;
    System.out.println(error);

    int i = 0;
    for(i=0; i<size; i++){

        if(array[0] == array[i]){
            error= error +1;
        }
        System.out.println(error);
    }

The 1 error is because you're comparing array[0] with array[0] , which is of course equal to itself. 1错误是因为您正在比较array[0]array[0] ,它当然等于它本身。

If you want to find all pairwise duplicates, you will need to do a double loop: 如果要查找所有成对的重复项,则需要执行一个双循环:

for(int i=0;i<size;i++){
    for(int j=i+1;j<size;j++){
        if(array[i] == array[j]){
            if(i!=j){
                error = error + 1;
            }
        }
    }
}

You'll notice a few things from this code: 您会从此代码中注意到几件事:

  • j starts at i+1, not at 0. j从i + 1开始,而不是0。
  • error is only incremented when i!=j 仅当i!= j时, error才会增加

The first is because you're taking turns with each element in your array to compare with every other element. 首先是因为您要轮流使用数组中的每个元素来与其他每个元素进行比较。 By the time its turn comes around (in the outer loop), it's already been compared to the elements before it, and should not be compared with them again. 轮到它出现时(在外部循环中),它已经与之前的元素进行了比较,因此不应再次与它们进行比较。

The second is because you'll end up comparing an element to itself for each outer loop. 第二个是因为您最终将为每个外部循环将一个元素与其自身进行比较。 You don't want to count it as an error . 您不想将其视为error

您将i从0开始。因此,第一个测试是if(array[0] == array[0]) ;)

Following code is fine but it returns 11. Not sure if it is what was expected. 可以使用以下代码,但返回11。不确定是否是预期的值。

public static void main(String[] args){
    int[] array = {23, 23, 0, 43, 545, 12, -55, 43, 12, 12, -999, -87, 12, 0, 0};
    int error = 0;
    for(int i=0;i<array.length;i++){
        for(int j=i+1;j<array.length;j++){
            if(array[i] == array[j]){
                if(i!=j){
                    error = error + 1;
                }
            }
        }
    }
    System.out.println(error);
}

I propose little bit complicated but hopefully more advanced solution. 我提出了一些复杂但希望更高级的解决方案。

package myjavaprogram;
import java.util.Arrays;

public class TestClass1 {
    public static void main(String[] args){
        int[] array = {23, 23, 0, 43, 545, 12, -55, 43, 12, 12, -999, -87, 12, 0, 0};
        //int[] array = {23, -22, 0, 43, 545, 12, -55, 43, 12, 0, -999, -87, 12};
        //int[] array = {23, -22, 0, 23};
        //int[] array = {23, -22, 23};
        calculate_duplicates(array);        
    }

    private static void calculate_duplicates(int[] array) {
        calculateUniqueNumbers(array);
    }

    private static void calculateUniqueNumbers(int[] array) {
        Pair[] pairs = new Pair[array.length];
        initializePairsAtrray(pairs, array);
        printPairsAtrray(pairs);

        System.out.println("array.length="+array.length);
        System.out.println("--------------------");

        // update pairs array taking in account duplicates duplicates
        for(int i = 0; i < array.length; i++) {
            System.out.println("array[i]="+array[i] + " i="+i);
            for(int j = i+1; j < array.length; j++) {
                System.out.println("array[j]="+array[j]+" j="+j);

                if(array[i] == array[j] && pairs[j].useDuringCount == true) {
                    pairs[i].occurance_num++;

                    pairs[j].occurance_num = 0;
                    pairs[j].useDuringCount = false;
                }

                if(array[i] == 0) {
                    pairs[i].occurance_num = 0;                    
                }
                if(array[j] == 0) {
                    pairs[j].occurance_num = 0;
                    pairs[j].useDuringCount = false;
                }                
            }
            pairs[i].useDuringCount = false;
            System.out.println("--------------------");
        }                
        printPairsAtrray(pairs);

        // calculate general number of duplicates (numbers whick are repeated 
        // in initial array)
        System.out.println("Duplicates in array:"+
                calculateDuplicatesNumber(pairs));        
    }

    private static void initializePairsAtrray(Pair[] pairs, int[] array) {
        for(int i=0;i<pairs.length;i++) {
            Pair p = new Pair();            
            p.occurance_num = 1;
            p.value = array[i];
            p.useDuringCount = true;
            pairs[i] = p;
        }
    }

    private static void printPairsAtrray(Pair[] pairs) {
        System.out.println("--------------------");
        for(int i=0;i<pairs.length;i++) {
            System.out.println("pairs["+i+"].occurance_num="+pairs[i].occurance_num);
            System.out.println("pairs["+i+"].value="+pairs[i].value);
            System.out.println("pairs["+i+"].useDuringCount="+pairs[i].useDuringCount);
            System.out.println("--------------------");
        }
    }

    private static int calculateDuplicatesNumber(Pair[] pairs) {
        System.out.println("-------------------- Duplicates:");
        int duplicates_num = 0;
        for(int i=0;i<pairs.length;i++) {
            if(pairs[i].occurance_num > 1) {
                duplicates_num++;
                System.out.println("number: "+pairs[i].value+" occurance_num " + pairs[i].occurance_num);
            }
        }
        return duplicates_num;
    }        
}    

class Pair {
    int value;
    int occurance_num;
    boolean useDuringCount;
}

Mykola 米科拉

您总是会遇到至少一个错误,因为当i = 0时, array[0] == array[i]在第一次迭代时为true。

Try a doubly nested for loop. 尝试双重嵌套的for循环。 Something like this 像这样

for (int i=0;i<size-1;i++){
  for (int j=i+1; j<size; j++) {
    error += (array[i] == array[j]) ? 1 : 0;
  }
}

In your code at 在您的代码中

int i=0;
for(i=0;i<size;i++){
    if(array[0]==array[i]){    //this condition runs true only for the first time. as i=0 here
        error=error+1;
    }
    System.out.println(error); //now here you had put the println(error) outside the if()-condition therefore it will be printed repeatedly value of error which is 1
}

You also need to "think Java". 您还需要“思考Java”。 Use Array.equals for the comparison. 使用Array.equals进行比较。 See the documentation here and some examples here 请参阅文件在这里和一些例子在这里

If you are going to make use of any collection, you can easiy findout the duplicates in the array 如果要使用任何集合,则可以轻松找出数组中的重复项

Example: 例:

 public static void main(String[] args) {
    boolean containsDuplicate =false;
    int[] intArray = new int[] {1,245,324,1,523};
    List<Integer> myObj = new ArrayList<Integer>();
    for(int id : intArray){
        if(myObj.contains(id)){
            containsDuplicate = true;
            System.out.println("Duplicate");
        }else{
            myObj.add(id);
        }
    }

}

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

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