原题
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
题目大意
给定一个整数数组,判断数组中是否包含重复元素。如果数组中任意一个数字出现了至少两次,你的函数应该返回true,如果每一个元素都是唯一的,返回false。
如果此题用如下的brute force会显示超出时间限制:
for(int i = 0; i < nums.length; i++) {
for(int j = i + 1; j < nums.length; j++) {
if(nums[i] == nums[j]) {
return true;
}
}
}
return false;
所以没办法暴力检索,下面是我的solution:
Solution 1 (Sorting is O(nlog n)。 TC:O(nlogn), SC:O(1)):
class Solution {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for(int i = nums.length - 1; i > 0 ; i--){
if(nums[i] == nums[i-1]) return true;
}
return false;
}
}
Solution 2 (hashtable)【TC: O(n), SC: O(n)】:
build up一个hashset去检验
class Solution {
public boolean containsDuplicate(int[] nums) {
Set <Integer> set = new HashSet<>(nums.length);
for(int num: nums){
if(set.contains(num)) return true;
set.add(num);
}
return false;
}
}