从数组中找出重复项
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 函数可以接受一个数组(或类型数组的对象)作为参数,用于初始化
本文由 Shuaiyin 创作,采用 知识共享署名4.0
国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: Sep 18,2019