求数组中第一个重复数字

题目描述

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中第一个重复的数字。
例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
返回描述:
如果数组中有重复的数字,函数返回true,否则返回false。
如果数组中有重复的数字,把重复的数字放到参数duplication[0]中。(ps:duplication已经初始化,可以直接赋值使用。)

 思路1:

我们知道hashmap的查找效率是O(1),很快。所以可以利用一个map<Integer, Integer>()来存储我们数组中遇到的每一个数字,

key为数组中数字,value为该数字出现的次数,遍历数组,当value为NULL时,将该value置为1,当不为空时,即之前出现过,所以就记录下来该值,并返回true.

import java.util.*;
public class Solution {
    // Parameters:
    //    numbers:     an array of integers
    //    length:      the length of array numbers
    //    duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;
    //                  Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++
    //    这里要特别注意~返回任意重复的一个,赋值duplication[0]
    // Return value:       true if the input is valid, and there are some duplications in the array number
    //                     otherwise false
    public boolean duplicate(int numbers[],int length,int [] duplication) {
        if(length <= 1){
            return false;
        }
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int i = 0;i<length;i++){
            if(map.get(numbers[i]) == null){
                map.put(numbers[i],1);
                continue;
            }else{
                duplication[0] = numbers[i];
                return true;
            }
        }
        return false;
    }
}

 

 该方法缺点即是还需要额外空间,map。 

 思路2:

我们知道map<Integer, Integer>(),里面存的是Integer类型,占4个字节(32位),而boolean占1个字节(8位)。

所以可以再new一个boolean数组,大小和number一样为length。遍历数组Number,因为每个元素是0<x<n的,

所以遇到一个元素,将其对应下标的boolean数组置为true,然后直至遇到该位为true时,就说明重复了。

同样的,该思路方法缺点同法1,也是需要额外空间。

那么,有没有一种方法不需要外空间的?

答案是肯定的。

请看思路3:

 思路3:

题目中说,number数组中的数字是有范围的,0<x<n,

故我们遍历数组,当一个数字被访问过后,可以设置对应位上的数 + n,

之后再遇到相同的数时,会发现对应位上的数已经大于等于n了,那么直接返回这个数即可。

哈哈哈,是不是很巧妙?这样的话,就不需要额外空间了。
 
 
Over...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
posted @ 2021-02-03 23:26  额是无名小卒儿  阅读(523)  评论(0编辑  收藏  举报