LeetCode:217. Contains Duplicate 解题

本文探讨了在整型数组中查找重复元素的有效方法。通过使用哈希表和排序技术,实现了快速检测数组中是否存在重复项的目标。文章提供了两种解决方案,并对比了它们的性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

217. Contains Duplicate
Difficulty: Easy
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

 

题目的意思是:给你个整型的数组,看看是否有元素相同,如果相同则返回true,如果没有则返回false。

第一思想是遍历检查,这个直接就时间超时了,这里就补贴代码了。后来看到Tags里面写但是hashtable,所以这里应该要和Hash相结合把。

写了个和hashmap应用解决的方法。

public class Solution {
    public boolean containsDuplicate(int[] nums) {
        int length = nums.length;
        if (length == 0) {
            return false;
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < length; i ++) {
            int temp = nums[i];
            if (map.containsKey(temp)) {
                return true;   
            } else {
                map.put(temp, i);
            }
        }
        return false;
    }
}

 但是提交后发现,非常慢,效率不高,不知道是否有人知晓比较好的解决方法,希望告知,谢谢。

 -------------------------------------------------------------------------------------------------

更新:6/4/2016 12:50:28 AM

经过排序之后,比较临近的元素这样效率更高!!

public class Solution {
    public boolean containsDuplicate(int[] nums) {
        Arrays.sort(nums);
        int length = nums.length;
        for (int i = 0; i < length; i ++) {
            if (i != length - 1 && nums[i] == nums[i + 1]){
                return true;
            } else if (i == length - 1) {
                return false;
            }
        }
        return false;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值