哈希表求出数组中第一个重复的数字

数组中重复的数字

http://www.nowcoder.com/questionTerminal/623a5ac0ea5b4e5f95552655361ae0a8

哈希表

自己的写法:

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)
但是相比第一种解法更快,空间上也消耗得更少。
推荐

剑指Offer题解 文章被收录于专栏

为了之后反复练习方便查阅。

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-01 10:56
点赞 评论 收藏
分享
05-26 10:24
门头沟学院 Java
qq乃乃好喝到咩噗茶:其实是对的,线上面试容易被人当野怪刷了
找工作时遇到的神仙HR
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务