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.
Example 1:
Input: [1,2,3,1] Output: true
Example 2:
Input: [1,2,3,4] Output: false
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2] Output: true
Solution 1: HashTable
Time complexity: O(n)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 |
// Author: Huahua, 48ms/16.5MB class Solution { public: bool containsDuplicate(vector<int>& nums) { unordered_set<int> s; for (int num : nums) if (!s.insert(num).second) return true; return false; } }; |
Solution 2: Sorting
Time complexity: O(nlogn)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 |
// Author: Huahua, 28ms/11.4MB class Solution { public: bool containsDuplicate(vector<int>& nums) { sort(begin(nums), end(nums)); for (int i = 1; i < nums.size(); ++i) if (nums[i] == nums[i - 1]) return true; return false; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment