【问题标题】:how I can sort and find the duplication in the array and return if there is a duplication?我如何排序并找到数组中的重复项并在有重复项时返回?
【发布时间】:2020-06-20 18:06:57
【问题描述】:

如何排序并找到数组中的重复项,如果有重复项则返回?

我有一个包含此代码的数组

 Scanner input = new Scanner(System.in);
            System.out.print("Enter the size of the array: ");
            int r = input.nextInt();
            int[] list = new int[r];
            init(list);

  static void init(int list[]) {
        Random random = new Random();
        for (int i = 0; i < list.length; i++) {
            int n = (int) (Math.random() * 50 + 1);
            list[i] = random.nextInt(50) + 1;
        }
    }

    static void print(int list[]) {
        for (int i : list) {
            System.out.print(i + " ");
        }
    }
}

我怎样才能用另一种方法对其进行排序并找到重复项

【问题讨论】:

标签: java arrays sorting duplicates


【解决方案1】:

从你的问题我明白你想要一个数组中的重复项。 这是一个使用幼稚方法的示例。如果你的数组很大,请不要使用它!!!

public static void main (String [] args) {
    System.out.println("Hello world");
    int [] myarray = {1,3,4,2,2,2,3};
    int [] duplicates = findDuplicates(myarray);
    System.out.println(Arrays.toString(duplicates));
}

private static int [] findDuplicates( int [] list) {
    int [] countingArray = new int[1];
    int n = 0;

    for (int i = 0; i < list.length; i++) {

        for (int j = i + 1 ; j < list.length; j++) { 

            if (list[i] == list[j]) { 
                boolean flag = true;

                for (int k = 0; k < countingArray.length; k++) {
                    if ((countingArray[k] == list[i])) {
                        flag = false;

                    }

                }

                if (flag) { 
                    if (n == countingArray.length) countingArray = resizeBy1(countingArray);
                    countingArray[n++] = list[i];
                }

            }
        }
    }

    return countingArray;

}
private static int [] resizeBy1(int [] s) {
    int [] newArray = new int[s.length +1];

    for (int i = 0; i< s.length; i++) {
        newArray[i] = s[i];
    }
    s = newArray;
    return s; 
}

如果您想了解高级方法,请查看Finding repetition in array

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2020-06-22
    • 2012-02-13
    • 1970-01-01
    • 2014-11-10
    • 2020-09-27
    • 1970-01-01
    相关资源
    最近更新 更多