LeetCode | Contains Duplicate

Contains Duplicate

 Total Accepted: 1522 Total Submissions: 3955My Submissions

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.

Show Tags







做法:最开始两重循环,以为不会卡,果真超时,后来想到用set,可以最后跟set和vector对象的size值进行判断。

自己的代码:

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
       set<int> temp;
       vector<int>::iterator p;
       for(p=nums.begin();p!=nums.end();p++)
       {
           temp.insert(*p);
       }
       if(temp.size()==nums.size())
          return false;
       else
          return true;
    }
};

然后我知道了可以这样写,两行,给跪,虽然时间还是100ms左右,现在想不到更好的办法orz:

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
       set<int> temp(nums.begin(),nums.end());
       return temp.size()!=nums.size();
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

posted on 2015-05-26 01:04  Tob__yuhong  阅读(107)  评论(0编辑  收藏  举报

导航