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

LeetCode 217 Contains Duplicate

时间:2016-10-30 07:13:52      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:should   hash   appear   pre   style   false   cti   etc   数组排序   

Problem:

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.

Summary:

判断数组中是否出现重复值。

Analysis:

1. 给数组排序后遍历,判断相邻两值是否相等。

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

2. Hash表建立数组中数字和出现次数的映射,判断是否大于1。

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

LeetCode 217 Contains Duplicate

标签:should   hash   appear   pre   style   false   cti   etc   数组排序   

原文地址:http://www.cnblogs.com/VickyWang/p/6012319.html

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