美文网首页
存在重复元素

存在重复元素

作者: 422ccfa02512 | 来源:发表于2020-12-09 23:25 被阅读0次

题目描述

难度级别:简单

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.

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

解题思路

哈希表

遍历数组元素,将数组元素存入哈希表中,若元素已在哈希表中输出true。

const containsDuplicate = function(nums) {
    const hashMap = new Map()

    for (let i = 0; i < nums.length; i++) {
        if (!hashMap.has(nums[i]))
            hashMap.set(nums[i], i)
        else
            return true
    }

    return false
};

排序

将数组排序后,若存在相同值则必然是连着的。

const containsDuplicate = function(nums) {
    nums.sort()
    for (let i = 0; i < nums.length; i++)
        if (nums[i] === nums[i+1]) return true
    
    return false
};

集合Set

通过集合去重数组,比较2者元素的数量。

const containsDuplicate = nums => 
    new Set(nums).size !== nums.length

题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/contains-duplicate

相关文章

  • 「算法」存在重复元素 & 存在重复元素 II

    00217 存在重复元素 题目描述 给定一个整数数组,判断是否存在重复元素。 如果任何值在数组中出现至少两次,函数...

  • LeetCode 217 存在重复元素.md

    题目描述 关键点 存在重复元素, 返回true, 不存在重复元素返回false 利用HashMap 不存在重复ke...

  • 存在重复元素

    leetcode

  • 存在重复元素

    题面: 给定一个整数数组nums,判断是否存在重复元素。如果任何值在数组中出现至少两次,函数返回 true。如果数...

  • 存在重复元素

    题目描述 难度级别:简单 Given an array of integers, find if the arra...

  • 存在重复元素

    给定一个整数数组,判断是否存在重复元素。如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不...

  • 存在重复元素

    给定一个整数数组,判断是否存在重复元素。如果存在一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素...

  • 存在重复元素

    题目信息 给定一个整数数组,判断是否存在重复元素。 如果存在一值在数组中出现至少两次,函数返回 true 。如果数...

  • LeetCode 第 217、219、220 题:存在重复元素

    LeetCode 第 217 题:存在重复元素 传送门:217. 存在重复元素。 给定一个整数数组,判断是否存在重...

  • LeetCode: 存在重复元素

    存在重复元素 English Description 给定一个整数数组,判断是否存在重复元素。 如果任何值在数组中...

网友评论

      本文标题:存在重复元素

      本文链接:https://www.haomeiwen.com/subject/euikgktx.html