Stupid Way: Cannot pass testing, too long time
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Solution { public: bool containsDuplicate(vector<int>& nums) { for(int i=0;i<nums.size();i++){ int cur=nums[i]; int comp=i+1; while(comp<nums.size()){ if(cur==nums[comp]) return true; comp++; } } return false; } }; |
1 2 3 4 5 6 7 8 9 10 11 | class Solution { public: bool containsDuplicate(vector<int>& nums) { set<int> s; for(int i=0;i<nums.size();i++){ if(s.find(nums[i])!=s.end()) return true; s.insert(nums[i]); } return false; } }; |
Tip: map element search O(log n), advantage compared to unordered_map: map is ordered
unordered_set has a convenient function count(): return 1 if key exists, 0 if not.
official definition: Count elements with a specific key
1 2 3 4 5 6 7 8 9 10 11 | class Solution { public: bool containsDuplicate(vector<int>& nums) { unordered_set<int> s; for(int i=0;i<nums.size();i++){ if(s.count(nums[i])) return true; s.insert(nums[i]); } return false; } }; |
SortingWay: update later
Reference:
http://www.bubuko.com/infodetail-827176.html
http://www.cplusplus.com/reference/unordered_map/unordered_map/count/
没有评论:
发表评论