Leetcode 217 Contains Duplicate

Source: Internet
Author: User

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

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.