原题链接: https://leetcode.com/problems/contains-duplicate/
1. 题目介绍
给出一个一维数组,数组中的元素全都是整数,判断数组中是否有元素重复。
如果有元素重复了,返回 true,如果没有元素重复,那就返回 false。
Example 1:
Input: [1,2,3,1]
Output: true
Example 2:
Input: [1,2,3,4]
Output: false
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2]
Output: true
2. 解题思路
2.1 方法1 先排序再找重复
首先将数组排序,排序之后遍历数组。如果某个数和它前面的数是一样的,那就是重复了。
实现代码
class Solution {
public boolean containsDuplicate(int[] nums) {
int length = nums.length;
if(length == 0) {
return false;
}
Arrays.sort(nums);
for(int i = 1;i<length;i++) {
if(nums[i] == nums[i-1]) {
return true;
}
}
return false;
}
}
2.2 方法2 借助Set
Set 是一种无序的集合。遍历数组,每遇到一个数,判断一下是否已经在set集合里面了,如果在的话,就是重复出现的,如果不在里面,那就是第一次出现,要把它放进set去。
实现代码
class Solution {
public boolean containsDuplicate(int[] nums) {
int length = nums.length;
if(length == 0) {
return false;
}
Set<Integer> set = new HashSet<>(length);
for(int i =0; i<length ; i++) {
if(set.contains(nums[i]) == true) {
return true;
}
set.add(nums[i]);
}
return false;
}
}