Problem:
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.
Summary:
Determines whether duplicate values appear in the array.
Analysis:
1. The array is sorted and traversed to determine whether the two adjacent values are equal.
1 classSolution {2 Public:3 BOOLContainsduplicate (vector<int>&nums) {4 intLen =nums.size ();5 6 sort (Nums.begin (), Nums.end ());7 for(inti =1; i < Len; i++) {8 if(Nums[i] = = Nums[i-1]) {9 return true;Ten } One } A - return false; - } the};
2. The hash table establishes the mapping of numbers and occurrences in the array, judging whether they are greater than 1.
1 classSolution {2 Public:3 BOOLContainsduplicate (vector<int>&nums) {4 intLen =nums.size ();5unordered_map<int,int>m;6 7 for(inti =0; i < Len; i++) {8 if(++m[nums[i]) >1) {9 return true;Ten } One } A - return false; - } the};
Leetcode 217 Contains Duplicate