LeetCode 217. Contains Duplicate

来源:互联网 发布:人工智能技术瓶颈 编辑:程序博客网 时间:2024/06/06 12:53

217. 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.

二、输入输出

三、解题思路

  • 像这种判断某个值出现过几次的最适合用hash-table map一类的了
  • 把值作为key,把出现的次数作为value。如果没有出现过就加进来,出现过就把出现次数加1
class Solution {public:    bool containsDuplicate(vector<int>& nums) {        int n = nums.size();        map<int, int> dict;        for (int i = 0; i < n; ++i) {            if  (dict.find(nums[i]) == dict.end()){                dict.insert(make_pair(nums[i], 1));            }else{                dict[nums[i]]++;            }        }        for (auto ite : dict){            if (ite.second >= 2) return true;        }        return false;    }};
原创粉丝点击