哈希表

自己的写法:

import java.util.*;
public class Solution {
    public boolean duplicate(int numbers[],int length,int [] duplication) {
        if(length == 0)
            return false;
        HashMap<Integer, Integer> count = new HashMap<>();
        for(int num : numbers){
            count.put(num, count.getOrDefault(num, 0)+1);
        }
        for(int i = 0; i < length; i++){
            if(count.get(numbers[i]) > 1){
                duplication[0] = numbers[i];
                return true;
            }
        }
        return false;
    }
}

时间复杂度为 O(n)
空间复杂度为 O(n)


以下是参考题解区的解法:

HashSet

import java.util.*;
public class Solution {
    public boolean duplicate(int numbers[],int length,int [] duplication) {
        if(length == 0)
            return false;
        Set<Integer> set = new HashSet<>();

        for(int i = 0; i < length; i++){
            if(set.contains(numbers[i])){
                duplication[0] = numbers[i];
                return true;
            }else{
                set.add(numbers[i]);
            }
        }
        return false;
    }
}

时间复杂度为 O(n)
空间复杂度为 O(n)
但是相比第一种解法更快,空间上也消耗得更少。
推荐