[Leetcode] Contains Duplicate

来源:互联网 发布:axure for mac 汉化 编辑:程序博客网 时间:2024/06/01 21:37

描述

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.

分析1

判断数组有没有重复元素。
使用哈希表,统计数组里每个数字出现的次数。

代码1

class Solution {public:    bool containsDuplicate(vector<int>& nums) {        unordered_map<int,int> m;        for (int i:nums) {            m[i]++;            if (m[i] > 1)                return true;        }        return false;    }};

分析2

同理可以用集合,代码如下。

代码2

class Solution {public:    bool containsDuplicate(vector<int>& nums) {        set<int> s;        for (int i:nums) {            if (s.count(i)) return true;            else s.insert(i);        }        return false;    }};
0 0