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.

  hash table用的还是比红黑树多啊,毕竟查找效率快!

solution:

bool containsDuplicate(vector<int>& nums) {
    if(nums.size() <= 1)
        return false;
    unordered_set<int> st;
    for (vector<int>::iterator it = nums.begin(); it != nums.end(); ++it)
    {
        if(st.find(*it) != st.end())
            st.insert(*it);
        else
            return true;
    }
    return false;
}

还有个关于元素重复的题目:Remove Duplicates from Sorted Array

posted @ 2015-06-23 11:27  Sawyer Ford  阅读(154)  评论(0编辑  收藏  举报