当前位置 博文首页 > Inmaturity_7的博客:算法练习帖--26--存在重复元素(Java)
给定一个整数数组,判断是否存在重复元素。
如果任意一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。
(题目来源:力扣(LeetCode))
示例 1:
输入: [1,2,3,1]
输出: true
示例 2:
输入: [1,2,3,4]
输出: false
示例 3:
输入: [1,1,1,3,3,4,3,2,4,2]
输出: true
1. 哈希表(官方题解)
class Solution {
public boolean containsDuplicate(int[] nums) {
//新建一个set集合,因为set集合不允许重复元素
//如果添加时已有此元素,会添加失败返回false
Set<Integer> set = new HashSet<Integer>();
for (int x : nums) {
if (!set.add(x)) {
return true;
}
}
return false;
}
}
2.排序
import java.util.HashMap;
import java.util.Map;
class Solution {
public static boolean containsDuplicate(int[] nums) {
if(nums==null){
return false;
}
int length=nums.length;
if(length<2){
return false;
}
//排序
Arrays.sort(nums);
//记录当前数字
int record=nums[0];
for (int i = 1; i < length; i++) {
//判断是否有重复数字
if(record==nums[i]){
return true;
}else{
record=nums[i];
}
}
return false;
}
}
cs