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.
给定整数数组,查找数组是否包含任何重复项。 如果数组中的任何值至少出现两次,则函数应返回true,如果每个元素都不同,则该函数返回false。
三种方法:
第一种:
var containsDuplicate = function(nums) { var len = nums.length; var arr = []; var flag = false; for(var i = 0;i < len-1;){ for(var j = i+1;j < len;){ if(nums[i] != nums[j]){ j++; }else{ flag = true; break; } } i++; } return flag; };
第二种:
var containsDuplicate = function(nums) {
var len = nums.length;
var arr = [];
var flag = false;
for(var i = 0;i < len;){
if(arr.indexOf(nums[i]) !== -1){
flag = true;
break;
}else{
arr.push(nums[i]);
i++;
}
}
return flag;
};
第三种:遍历数组,nums[i]中取绝对值,在arr中设置arr[Math.abs(nums[i])]的值;
首先,判断nums[i]的正负,若arr[Math.abs(nums[i])]未定义则nums[i]正时值为1,负为-1,正负都判断后则为0;下标为0,未定义为0,值为0 则设置flag为true;
var containsDuplicate = function(nums) { var len = nums.length; var arr = []; var flag = false; for(var i = 0;i < len;){ var index =Math.abs(nums[i]); if(nums[i] < 0){ if(arr[index] == 1){ arr[index] = 0; }else if(arr[index] == -1){ flag = true; break; }else{ arr[index] = -1; } }else if(nums[i] > 0){ if(arr[index] == 1){ flag = true; break; }else if(arr[index] == -1){ arr[index] = 0; }else{ arr[index] = 1; } }else{ if(arr[index] !== 0){ arr[index] = 0; }else if(arr[index] === 0){ flag = true; break; } } i++; } return flag; };