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.
答案:
判断一个整型数组里是否有重复的元素,用哈希表。
建立一个set集合,若集合中已有该元素,则返回true,否则返回false.
1 class Solution { 2 public: 3 bool containsDuplicate(vector<int>& nums) { 4 int n=nums.size(); 5 if(n<2){ 6 return false; 7 } 8 set<int> temp; 9 for(int i=0;i<n;i++){ 10 if(temp.count(nums[i])==1){ 11 return true; 12 } 13 else{ 14 temp.insert(nums[i]); 15 } 16 } 17 return false; 18 } 19 };