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 ele ment is distinct.
Solution One:
Sort, and then compare whether adjacent elements are the same. Time complexity O (NLOGN), Space complexity O (1)
classSolution { Public: BOOLContainsduplicate (vector<int>&nums) { if(Nums.size () <=1) return false; Sort (Nums.begin (), Nums.end ()); for(inti =1; I < nums.size (); i + +) { if(nums[i-1] ==Nums[i])return true; } return false; }};
Solution Two:
Use Unordered_map to record the elements that have occurred. Time complexity O (n), spatial complexity O (n)
classSolution { Public: BOOLContainsduplicate (vector<int>&nums) { if(Nums.size () <=1) return false; Unordered_map<int,BOOL>m; for(inti =0; I < nums.size (); i + +) { if(M[nums[i]] = =true) return true; M[nums[i]]=true; } return false; }};
"Leetcode" 217. Contains Duplicate (2 solutions)