码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】217 - Contains Duplicate

时间:2015-08-02 16:35:11      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

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.

Solution 1: sort后相邻位比较

 1 class Solution {
 2 public:
 3     bool containsDuplicate(vector<int>& nums) {     //runtime:40ms
 4         if(nums.size()<=1)return false;
 5         sort(nums.begin(),nums.end());
 6         for(int i=1;i<nums.size();i++){
 7             if(nums[i-1]==nums[i])return true;
 8         }
 9         return false;
10     }
11 };

Solution 2: map记录已存在的int

 1 class Solution {
 2 public:
 3     bool containsDuplicate(vector<int>& nums) {     //runtime:104ms
 4         if(nums.size()<=1)return false;
 5         map<int,bool> m;
 6         for(int i=0;i<nums.size();i++){
 7             if(m[nums[i]]==true)return true;
 8             m[nums[i]]=true;
 9         }
10         return false;
11     }
12 };

 

【LeetCode】217 - Contains Duplicate

标签:

原文地址:http://www.cnblogs.com/irun/p/4695783.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!