![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/165eb2b07e2c4d969d6ee3f757764ee4.jpeg#pic_center)
需求
给你一个整数数组 nums 。如果任一值在数组中出现 至少两次 ,返回 true ;如果数组中每个元素互不相同,返回 false 。
示例 1:
输入:nums = [1,2,3,1]
输出:true
示例 2:
输入:nums = [1,2,3,4]
输出:false
示例 3:
输入:nums = [1,1,1,3,3,4,3,2,4,2]
输出:true
提示:
1 <= nums.length <= 105
-109 <= nums[i] <= 109
版本1 用Set
看完题目,感觉还挺简单的. 无非就是定义一个 Set 容器, 然后遍历数组, 判断容器内是否存在元素, 存在的话就返回 true, 不存在就将其存进去. 遍历完就OK 了.
public boolean containsDuplicate(int[] nums) {
int length = nums.length;
// 定义容器
Set<Integer> set = new HashSet<>(length);
for( int i = 0; i < length; i++ ){
if (set.contains(nums[i])) {
return true;
}
set.add(nums[i]);
}
return false;
}
执行完 很丝滑, 就是时间用的有点多啊.
版本2 用Set
提示中说 1 <= nums.length <= 105
, 也就是说数组的长度有可能是1, 那么如果是1的话, 那就自然不存在一个数字在数组中出现两次了, 直接返回 false 即可.
public boolean containsDuplicate(int[] nums) {
int length = nums.length;
if( length == 1 ){
return false;
}
Set<Integer> set = new HashSet<>(length);
for( int i = 0; i < length; i++ ){
if (set.contains(nums[i])) {
return true;
}
set.add(nums[i]);
}
return false;
}
执行结果, 时间降下来了不少. 但是还是有点多啊.
版本3 用Set
小改:
public boolean containsDuplicate(int[] nums) {
int length = nums.length;
if( length > 1 ){
Set<Integer> set = new HashSet<>(length);
for( int i = 0; i < length; i++ ){
if (set.contains(nums[i])) {
return true;
}
set.add(nums[i]);
}
}
return false;
}
耗时还是长
版本4 用Set
小改:
public boolean containsDuplicate(int[] nums) {
int length = nums.length;
if( length > 1 ){
Set<Integer> set = new HashSet<>(length);
for( int i = 0; i < length; i++ ){
if ( !set.add(nums[i]) ) {
return true;
}
}
}
return false;
}
耗时降到 9 ms 了.
版本5 用Map
上面的几种写法耗时依然很多啊, 难道是 set 性能问题??? 试试 Map ?
public boolean containsDuplicate(int[] nums) {
int length = nums.length;
if( length > 1 ){
Map<Integer, Integer> map = new HashMap<>(length);
for( int i = 0; i < length; i++ ){
if( map.containsKey(nums[i]) ){
return true;
}
map.put(nums[i], i);
}
}
return false;
}
耗时依旧啊啊啊啊啊~~~
版本6
前面的版本都是 在数组不是排序的情况下进行的, 那么我们给数组排个序, 是不是有什么新的收获呢?
public boolean containsDuplicate(int[] nums) {
int length = nums.length;
if( length > 1 ){
// 先给数组排序
Arrays.sort( nums );
for( int i = 0; i < length - 1; i++ ){
if( nums[i] == nums[i+1] ){
return true;
}
}
}
return false;
}
好吧~ 我抑郁了~~~
结尾
以上 是我对重复元素的一些遐想和延伸, 可能不是最优解, 但是算法的优化嘛 本身就是一个思索的过程, 能在这个思索和迭代的过程中有所收获和乐趣就是在成长了, 欢迎大家一起来交流更多的解答…