首页 > 解决方案 > 如何仅使用基本循环删除 int 数组的重复项

问题描述

该代码需要删除数组中的所有重复整数,但要保持简单。如果没有 system.arraycopy 或任何复杂的东西,就不能使用 set 或任何“超出”知识循环的东西。它是一个接收数字数组的构造函数,应该检查数字是否重复并创建一个没有重复的数组

例如:

{1,2,5,5,2,4,5,1} 将是 {1,2,5,4} 所以它应该创建一个数字大小不重复的数组。

试图创建一个循环来计算数字是否重复本身,只有如果不是,它才会添加它,但这不是最好的主意,因为它不会计算至少重复一次的数字

int repeat = 0;enter code here
        int counter = 0;
        if(se.length < 2)
        {
            System.out.println("Array smaller than 2, please change the size!");
            return;
        }
        for(int i = 0; i < se.length; i++)
        {
            for(int j = 0; j < se.length; j++)
                if(se[i] == se[j])
                {
                    repeat++;
                }
            if(repeat == 0)
                counter++;
            repeat = 0;
        }

标签: java

解决方案


您可以尝试以下方法:

public static void removedups(int se[]) {
    int repeat = 0;
    int counter = 0;
    if(se.length < 2) {
        System.out.println("Array smaller than 2, please change the size!");
        return;
    }
    //Find out all the duplicates and replace with 0
    boolean isZeroPresent = false;
    int zeroindex = -1;
    for(int i = 0; i < se.length; i++) {
        for(int j = i + 1; j < se.length; j++) {
            if(se[i] == se[j]) {
                if(se[i] == 0 && !isZeroPresent) {
                    isZeroPresent = true;
                    zeroindex = i;
                }
                se[j] = 0;
            }
        }
    }

    //find the exact count of the array which does not contains duplicates
    int customIndex = 0;
    for(int i = 0; i < se.length; i++) {
        System.out.println(se[i]);
        if(isZeroPresent && zeroindex == i) {
            customIndex++;
            continue;
        }
        if(se[i] == 0) {
            continue;
        }
        customIndex++;
    }

    //create new array which will hold all the unique values and return 
    int arr[] = new int[customIndex];
    int j = 0;
    for(int i = 0; i < customIndex; i++) {
        if(se[i] == 0) {
            if(zeroindex == i) {
                arr[j] = se[i];
                j++;
            }
            continue;
        }
        arr[j] = se[i];
        j++;
    }
    System.out.println("-----------------");
    printArr(arr);
}

public static void printArr(int arr[]) {
    for(int i = 0; i < arr.length; i++) {
        System.out.println(arr[i]);
    }
}

推荐阅读