数组 - 找出重复项

从数组中找出重复项

Description

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:

    Input: [1,2,3,1]
    Output: true
    
    Input: [1,2,3,4]
    Output: false
    
    Input: [1,1,1,3,3,4,3,2,4,2]
    Output: true
    

Programmer

  • 普通方法
var containsDuplicate = function(nums) {
    
    for(let i = 0; i < nums.length; i++) {
        for (let j = i+1; j < nums.length; j++) {
            if(nums[i] == nums[j]) {
                return true;
            }
        }
    }
    
    return false;
};
  • Set 数据机构

    var containsDuplicate = function(nums) {
    
        return new Set(nums).size < nums.length
    
    };
    

Idea:

  • 普通方法

    • 遍历数组每一项,每一项与剩下的进行比较
    • 嵌套 for 循环
  • Set 方法

    • Set 的成员的值是唯一的,没用重复的项
    • Set 函数可以接受一个数组(或类型数组的对象)作为参数,用于初始化
# ARTS  array 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×