Day80:-输出数组中重复的数字

49 阅读1分钟

43、输出数组中重复的数字

题目:在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。

例如,如果输入长度为7的数组[2,3,1,0,2,5,3],那么对应的输出是2或者3。存在不合法的输入的话输出-1。数据范围:0≤n≤10000 。
进阶:时间复杂度O(n) ,空间复杂度O(n)

示例

输入:[2,3,1,0,2,5,3]
输出:2
说明:2或者3 都是对的

思路

利用HashMap的key储存数组中的值,value来储存出现次数,然后在遍历出value最大值

具体实现

public static void main(String[] args) {
  int[] num = {2,3,1,3,2,5,3};
    System.out.println(MaxofArr(num));
}
static int MaxofArr(int[] arr){
    Map<Integer,Integer> map = new  HashMap();
    for (int i = 0;i < arr.length;i++){
        if (!map.containsKey(arr[i])){
            map.put(arr[i],1);
        }else {
            map.put(arr[i],map.get(arr[i])+1);
        }
    }
    int max = 0;
    for (int temp:map.keySet()){
        max = map.get(temp) > max ? map.get(temp) : max;
    }
    return max;
}

时间复杂度:O(n);分开遍历了数组和keyset;

空间复杂度:O(n);利用了map;