15.存在重复元素

15.存在重复元素

一、题目

给定一个整数数组,判断是否存在重复元素。
如果存在一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。
链接:https://leetcode-cn.com/problems/contains-duplicate/solution/cun-zai-zhong-fu-yuan-su-by-leetcode-sol-iedd/
来源:力扣(LeetCode)

二、示例

示例①

输入: [1,2,3,1]
输出: true

示例②

输入: [1,2,3,4]
输出: false

三、代码实现

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

测试后能行,就是搞不懂为什么超出时间限制,明明只有一个循环

方法一:排序

public static boolean containsDuplicateBySort(int[] nums){
        Arrays.sort(nums);
        int n = nums.length;
        for (int i = 0;i < n - 1;i++){
            if (nums[i] == nums[i+1]){
                return true;
            }
        }
        return false;
    }

这个应该也是差点超出时间限制,sort有个循环,外面有层循环,这个过了为什么我那个没过-_-

方法二:哈希表

 public static boolean containDuplicateBySet(int[] nums){
        HashSet<Integer> integers = new HashSet<>();
        for (int num : nums){
            if (!integers.add(num)){
                return true;
            }
        }
        return false;
    }

算是最好的方法,评论里的方法懒得找了,耗时一般,

四、复杂度分析

排序

  • 时间复杂度O(NlogN)
  • 空间复杂度O(logN)

哈希表

  • 时间复杂度O(N)
  • 空间复杂度O(N)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值