LeetCode 217. Contains Duplicate

題目

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.

翻譯

給一個陣列,確認陣列中是否有重複的元素

思路

解題方向與169. Majority Element完全相通,使用map,當一個元素count = 2時,回傳true,迴圈如果跑完回傳false。

解題

/**
 * @param {number[]} nums
 * @return {boolean}
 */
var containsDuplicate = function(nums) {
    var keep = [];
    for(var i in nums){
        if(keep.indexOf(nums[i])<0){
            keep.push(nums[i]);
        } else {
            return true;
        }
    }
    return false;
};

results matching ""

    No results matching ""