題目地址:
https://www.lintcode.com/problem/contains-duplicate/description
給定一個數組,判斷其中是否有重複。用哈希表去重後看一下size和原數組長度是否相等即可,若不等則返回true。代碼如下:
import java.util.HashSet;
import java.util.Set;
public class Solution {
/**
* @param nums: the given array
* @return: if any value appears at least twice in the array
*/
public boolean containsDuplicate(int[] nums) {
// Write your code here
if (nums == null || nums.length == 0) {
return true;
}
Set<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
return nums.length != set.size();
}
}
時空複雜度。