[leetcode] Contains Duplicate
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.
Have you met this question in a real interview?
思路:
1,哈希法:用一个set记录所有出现过的数字,若有冲突,则含有重复元素;若没有冲突,则不含有重复元素。此方法时间复杂度为O(n),空间复杂度为O(n)
1 class Solution 2 { 3 public: 4 bool containsDuplicate(vector<int> &nums) 5 { 6 set<int> S; 7 for(int i=0; i<nums.size(); i++) 8 { 9 if(S.find(nums[i]) == S.end()) 10 S.insert(nums[i]); 11 else 12 return true; 13 } 14 return false; 15 } 16 };
2,排序法:先将该数组排序,然后从i=1开始,num[i-1]与nun[i]两两比较, 若存在相等的情况,则含有重复元素,否则不含有重复元素,此方法时间复杂度为O(nlogn), 空间复杂度为O(1)。
1 class Solution 2 { 3 public: 4 bool containsDuplicate(vector<int> &nums) 5 { 6 sort(nums.begin(), nums.end()); 7 for(int i=1; i<nums.size(); i++) 8 if(nums[i-1] == nums[i]) 9 return true; 10 11 return false; 12 } 13 };