No.217 Contains Duplicate

No.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.

Tags: Array Hash Table

 

  判断数组nums中是否有重复元素:有,返回true;无,即所有元素均不重复,返回false
  根据提示——哈希表,有了思路[亲,你的大脑呢]
  题意刚好理解反了!!!
 
 1 #include "stdafx.h"
 2 #include <set>
 3 #include <vector>
 4 #include <iostream>
 5 
 6 using namespace std;
 7 
 8 class Solution
 9 {
10 public:
11     bool containsDuplicate(vector<int> &nums)
12     {//判断数组nums中是否有重复元素:有,返回true;无,即所有元素均不重复,返回false
13      //根据提示——哈希表,有了思路[亲,你的大脑呢]
14      //题意刚好理解反了!!!
15         int size = nums.size();
16         if(size == 0)//题意理解问题!!!
17             return false;
18         set<int> exist;
19         for(int i=0; i<size; i++)
20         {
21             if(exist.find(nums[i]) != exist.end())
22                 return true;
23             else
24                 exist.insert(nums[i]);
25         }
26         return false;
27     }
28 };
29 
30 int main()
31 {
32     Solution sol;
33     int data[] = {1};
34     vector<int> test(data,data+sizeof(data)/sizeof(int));
35     cout << boolalpha << sol.containsDuplicate(test);
36 
37 }

 

posted @ 2015-06-10 15:29  人生不酱油  阅读(115)  评论(0编辑  收藏  举报