数组中重复的数字

本贴最后更新于 2250 天前,其中的信息可能已经东海扬尘

题目描述

在一个长度为 n 的数组里的所有数字都在 0 到 n-1 的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为 7 的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字 2。

解题思路

我们需要一个结构,用来存放数据是否出现过,而且方便查找是否存在。

  • 第一种思路就是用 map;
  • 稍微高级点就是用数字的二进制;
  • 高级思路是用数组本身作为存放数据的结构,因为题目保证所有数字在 0~n-1 之间,可以利用索引来存储数据。

代码

代码 1(map)

public class Solution {
    public boolean duplicate(int numbers[],int length,int [] duplication) {
        if (numbers == null || numbers.length == 0)
            return false;
        int[] help = new int[length];
        help[0] = -1;
        for (int i = 0; i < length; i++) {
            if (numbers[i] >= length || numbers[i] < 0)
                return false;
            if (help[numbers[i]] == numbers[i]) {
                duplication[0] = numbers[i];
                return true;
            }
            help[numbers[i]] = numbers[i];
        }
        return false;
    }
}

代码 2(数组本身)

public class Solution {
    public boolean duplicate(int numbers[],int length,int [] duplication) {
        if (numbers == null || numbers.length == 0)
            return false;
        for ( int i= 0 ; i<length; i++) {
            int index = numbers[i];
            if (index >= length)
                index -= length;
            if (numbers[index] >= length) {
                duplication[0] = index;
                return true;
            }
            numbers[index] = numbers[index] + length;
        }
        return false; 
    }
}

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...