1. 程式人生 > >【LeetCode & 劍指offer刷題】陣列題4:Contains Duplicate

【LeetCode & 劍指offer刷題】陣列題4:Contains Duplicate

【LeetCode & 劍指offer 刷題筆記】目錄(持續更新中...)

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 element is distinct.
Example 1: Input: [1,2,3,1] Output: true Example 2: Input: [1,2,3,4] Output: false Example 3: Input:
[1,1,1,3,3,4,3,2,4,2] Output: true
C++   /* 問題:判斷一個數組是否含重複元素 方法:用map統計每個元素出現的次數 O(n),O(n) 改進,可以sort後判斷,這樣就不需要額外空間了,用時間換空間
*/ #include <map> class Solution { public :     bool containsDuplicate ( vector < int >& nums )     {         unordered_map < int , int > dict ;//用hash表,平均訪問時間為O(1)(用unordered_set也可以)         for ( int num : nums ) // 統計每個元素的出現次數         {             dict [ num ]++; //首次呼叫 operator[] 以零初始化計數器             if ( dict [ num ] > 1 ) return true ;         }         return false ;     } };