Leetcode "Hash list": Contains Duplicate && Contains Duplicate II

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.