217. 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.
Main topic:
Given an array of integers, determine whether the array contains duplicate elements. If any number in the array appears at least two times, your function should return true if each element is unique and return false.
Problem Solving methods:
Sorts the array first to compare whether the two adjacent elements are equal.
Precautions:
C + + code:
4~18 the behavior of the shell, using sort (Nums.begin (), Nums.end ()) instead.
1 classSolution {2 Public:3 BOOLContainsduplicate (vector<int>&nums) {4 inttmp;5 intJ;6 if(Nums.empty () | | Nums.size () = =1)return false;7 for(intGap=nums.size ()/2;gap>0; gap/=2)8 {9 for(intI=gap;i<nums.size (); i++)Ten { Onetmp=Nums[i]; A for(j=i;j>=gap&&tmp<nums[j-gap];j-=Gap) - { -nums[j]=nums[j-Gap]; the } -nums[j]=tmp; - } - } + for(intI=0; I<nums.size ()-1; i++) - { + if(nums[i]==nums[i+1])return true; A } at return false; - } -};
217. Contains Duplicate (c + +)