题目链接:https://www.nowcoder.com/practice/623a5ac0ea5b4e5f95552655361ae0a8?tpId=13&&tqId=11203&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

  思路:哈希,我们使用 map 将所有的数字出现的次数都先保存下来,然后遍历数组,如果出现次数大于 1 则输出保存结果并且返回 true;否则返回 false。(题解区中先给数组排序然后在判断这样结果不对,无法保证第一个重复的数字被返回,返回的是最小的重复的数字)(以及题解区中介绍的不断的将某一个位置的数字置换到相应的位置上也无法保证我们找到的重复的就是第一个数字。)

import java.util.*;
//[6,3,2,0,2,5,0]
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) {
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < length; ++ i) {
            if(map.get(numbers[i]) == null) {
                map.put(numbers[i], 1);
            } else {
                map.put(numbers[i], map.get(numbers[i]) + 1);
            }
        }
        for(int i = 0; i < length; ++ i) {
            if(map.get(numbers[i]) > 1) {
                duplication[0] = numbers[i];
                return true;
            }
        }
        return false;
    }
}