哈希表求出数组中第一个重复的数字
数组中重复的数字
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题解 文章被收录于专栏
为了之后反复练习方便查阅。
