Skip to content

[leetcode]217.存在重复元素 #40

Description

@MagicalBridge

方法一:排序

在对数字从小到大排序之后。数组的重复元素一定出现在相邻的位置,因此我们可以扫描已经排序的数组,每次判断相邻的两个元素是否相等,如果相等则说明存在重复的元素。

/** * @param {number[]} nums * @return {boolean} */varcontainsDuplicate=function(nums){// 将数组做升序排列nums.sort((a,b)=>a-b);// 数组的长度constn=nums.length;// 循环遍历数组 因为下面需要有 i+1的操作,所以这里n-1是取不到的。for(leti=0;i<n-1;i++){if(nums[i]===nums[i+1]){returntrue;}}returnfalse;};

复杂度分析

  • 时间复杂度: O(NlogN),其中N为数组的长度。需要对数组进行排序。
  • 空间复杂度: O(logN),其中N为数组的长度,注意在这里我们应当考虑递归调用栈的深度

方法二:哈希表

对于数组中的每个元素,我们将它插入到哈希表中,如果插入一个元素的时候发现这个元素已经存在于哈希表中,则说明存在重复的元素。

/** * @param {number[]} nums * @return {boolean} */varcontainsDuplicate=function(nums){constset=newSet();for(constxofnums){if(set.has(x)){returntrue;}set.add(x);}returnfalse;};

复杂度分析:

  • 时间复杂度:O(N),其中N为数组的长度。
  • 空间复杂度:O(N),其中N为数组的长度。

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions