[LeetCode] Contains Duplicate
2015-06-11 13:48
309 查看
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. Sort the array and then compare
2. Use unordered_set with Time complexity O(n) and space complexity O(n)
Another highly mathematical solution:
http://bookshadow.com/weblog/2015/06/03/leetcode-contains-duplicate-iii/
The difference between map, hash_map, unordered_map and unordered_set:
http://blog.csdn.net/u013195320/article/details/23046305
twice in the array, and it should return false if every element is distinct.
1. Sort the array and then compare
class Solution { public: bool containsDuplicate(vector<int>& nums) { vector<int> array=nums; std::sort(array.begin(),array.end()); for(int i=1;i<array.size();i++) { if(array[i]==array[i-1]) return true; } return false; } };
2. Use unordered_set with Time complexity O(n) and space complexity O(n)
class Solution { public: bool containsDuplicate(vector<int>& nums) { unordered_set<int> aset; for(auto i : nums) { if(aset.find(i)!=aset.end()) return true; aset.insert(i); } return false; } };
Another highly mathematical solution:
http://bookshadow.com/weblog/2015/06/03/leetcode-contains-duplicate-iii/
The difference between map, hash_map, unordered_map and unordered_set:
http://blog.csdn.net/u013195320/article/details/23046305
相关文章推荐
- 40 Key Computer Science Concepts Explained In Layman’s Terms
- 【leetcode】【217】Contains Duplicate
- PyBrain使用简介
- Failed to import package with error: Couldn't decompress package
- Factorial Trailing Zeroes——数学类
- Factorial Trailing Zeroes
- 【Leetcode Database】Delete Duplicate Emails
- Mail发送外部邮件
- Fair Scheduler中的Delay Schedule分析
- async & await 的前世今生
- 强人工智能:抑制神经元的意义
- K smallest in array with detail explanation
- rails日记1
- http://blog.csdn.net/ya2dan/article/details/7395458
- 创建四个控制器(Main)
- Fibonacci Again
- Training:计算几何基础
- hdoj 1702 ACboy needs your help again!【数组模拟+STL实现】
- ubuntu14.04 安装PIL库出现OError: decoder jpeg not available 的解决方案
- postfix收发邮件大小和webmail空间大小设定