1. Contains Duplicate
Topic links
Title Requirements:
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.
The code is as follows:
1 classSolution {2 Public:3 BOOLContainsduplicate (vector<int>&nums) {4unordered_map<int,int>HashMap;5 intSZ =nums.size ();6 for(inti =0; I < sz; i++)7hashmap[nums[i]]++;8 9unordered_map<int,int>::iterator ITR =Hashmap.begin ();Ten for(; ITR! = Hashmap.end (); itr++) One { A if(Itr->second >=2) - return true; - } the - return false; - } -};
2. Contains Duplicate II
Topic links
Title Requirements:
Given an array of integers and a integer K, find out whether there there is II distinct indices i and J in the array such that nums[i] = Nums[j] and the difference between I andJ are at most k< /c5>.
1 classSolution {2 Public:3 BOOLContainsnearbyduplicate (vector<int>& Nums,intk) {4unordered_map<int,int>HashMap;5 intSZ =nums.size ();6 for(inti =0; I < sz; i++)7 {8 if(Hashmap.find (nums[i])! =hashmap.end ())9 {Ten intj =Hashmap[nums[i]]; One if(I-j <=k) A return true; - Else -Hashmap[nums[i]] =i; the } - Else - { -Hashmap[nums[i]] =i; + } - } + A return false; at } -};
Leetcode "Hash list": Contains Duplicate && Contains Duplicate II