数组中某值是否重复问题

public static ArrayList<Integer> repeat(int[] array) {
    ArrayList<Integer> result = new ArrayList<>();
    int[] exists = new int[11];
    for (int i = 0; i < array.length; i++) {
        int value = array[i];
        // 如果当前位置已经为1,则表示重复
        if (exists[value] == 1) {
            result.add(value);
        } else {
            // 否则将当前位置设置为1
            exists[value] = 1;
        }
    }
    return result;
}

分析:

在明确数组中数是有一定范围的情况下,可以先定义另一个数组exist

该数组的长度为原数组中数的范围。

创建一个数组result储存重复值

遍历一遍原数组,每遍历到一个数就把其exist对应位置(如遍历到10则exist的第10个位置)的书变为1。

如果再次遍历到相同的数,判断到exist对应位置为1则代表有重复数并输出进result数组

此方法可以用于string

在一个string中

利用string.charAt(int)来获取每个位置的字符

利用相同方法创建26位的数组

利用同样的方法遍历一遍

注:在string时要注意ASCII代码表示的‘a’为97,在数组对应上要减去97或者‘a’如exists[value-97]==1部分