217. 存在重復(fù)元素 - 力扣(LeetCode) (leetcode-cn.com)
難度:簡(jiǎn)單
題目描述:給定一個(gè)整數(shù)數(shù)組雁芙,判斷是否存在重復(fù)元素拍柒。
如果存在一值在數(shù)組中出現(xiàn)至少兩次袖外,函數(shù)返回 true 唠摹。如果數(shù)組中每個(gè)元素都不相同绵估,則返回 false 炎疆。
分析
1- 創(chuàng)建一個(gè)哈希表,將數(shù)組中的元素添加到哈希表中国裳,
此處使用set.add()方法的原因是方法返回值為布爾類型并且官方對(duì)于返回值這樣解釋
true if this set did not already contain the specified element
所以不需要使用set.contains()判斷是否存在此元素
2- 排序后判斷前后兩個(gè)元素是否相等 排序后數(shù)組為有序數(shù)組形入,如果存在兩數(shù)相等,則兩數(shù)位置為前后位置
解題
方法一
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> sets = new HashSet<>();
for (int num :
nums) {
if (!sets.add(num)) {
return true;
}
}
return false;
}
}
方法二
class Solution {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == nums[i+1]){
return true;
}
}
return false;
}
}