LeetCode Contains Duplicate

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.

Example 1:

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

Example 2:

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

Example 3:

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

判断一个数组中是否有重复元素,简单题,hash即可。沾欣欣的光,也来用用unordered_map 🙂 完整代码如下:

class Solution {
public:
    bool containsDuplicate(vector<int>& nums)
    {
        unordered_map<int, int> hash_table;
        for (int i = 0; i < nums.size(); i++) {
            hash_table[nums[i]]++; // 如果元素不存在hash_table中,会自动插入,并赋值为0,++之后为1
            if (hash_table[nums[i]] > 1)
                return true;
        }
        return false;
    }
};

本代码提交AC,用时49MS。
当然也可以用set或map这种树结构来实现,如果知道数据范围,也可以用桶来实现。

1 thought on “LeetCode Contains Duplicate

  1. Pingback: LeetCode Contains Duplicate II | bitJoy > code

Leave a Reply

Your email address will not be published. Required fields are marked *