217. Contains Duplicate
Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
1 2 3 4 5 6 7 8 9 10 11
| class Solution { public: bool containsDuplicate(vector<int>& nums) { unordered_set<int> s; for(auto& n : nums) { if(s.count(n)) return true; s.insert(n); } return false; } };
|
- Time : O(nlogn)
- Space : O(1)
1 2 3 4 5 6 7 8 9 10
| class Solution { public: bool containsDuplicate(vector<int>& nums) { sort(nums.begin(), nums.end()); for(int i = 1; i < nums.size(); i++) { if(nums[i] == nums[i-1])return true; } return false; } };
|
1 2 3 4 5 6
| class Solution { public: bool containsDuplicate(vector<int>& nums) { return nums.size() != unordered_set<int>(nums.begin(), nums.end()).size(); } };
|