題目: 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

 

說明:

一組陣列,如果數字有重複,顯示true,

沒有則顯示false

 

做法:

當初我用bubble sort做,雖然答案正確,但他會timeout......

所以我就決定善用工具~使用set函數

set重複就不會計算,所以我們只要比2個陣列的size大小即可

比較大代表重複,一樣代表不重複

 

程式碼:

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
      set <int> s(nums.begin(),nums.end());
        if(s.size()<nums.size())return true;
        return false;
    }
};

 

 

 

arrow
arrow

    kyo 發表在 痞客邦 留言(0) 人氣()