您的位置:首页 > 大数据 > 人工智能

Leetcode NO.217 Contains Duplicate

2015-06-25 04:28 465 查看
本题题目要求如下:

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.

我的算法很直接,就是用hashset,遍历数组,如果该元素已经存在于hashset中,则是重复的,如果不在hashset中,则继续插入

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        unordered_set<int> hashset;
        for (int i = 0; i < nums.size(); ++i) {
            if (hashset.find(nums[i]) != hashset.end()) {
                return true;
            }
            else {
                hashset.insert(nums[i]);
            }
        }
        return false;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: