217. Contains Duplicate
2016-03-15 22:49
357 查看
1.Question
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.
2.Code
3.Note
a.该问题第一点想到哈希表,设置些标记就好了。
b.这道题有个trick是,可以通过int map[1000000]来作哈希表,简单粗暴,针对于leetcode 上的这道题还能节省将近一半的时间。但是缺点就是相对来说消耗大量的内存。所以在考虑问题是,也要权衡时间复杂度和空间复杂度,针对实际情况进行选择。
c.这道题还有个解法是先将数组进行排序,如果出现相邻两个相等,则return true.排序只需要以下一个命令。
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.
2.Code
class Solution { public: bool containsDuplicate(vector<int>& nums) { unordered_map<int, int> map; for(int i = 0; i < nums.size(); ++i) { if(map[nums[i]] == 1) return true; else map[nums[i]] = 1; } return false; } };
3.Note
a.该问题第一点想到哈希表,设置些标记就好了。
b.这道题有个trick是,可以通过int map[1000000]来作哈希表,简单粗暴,针对于leetcode 上的这道题还能节省将近一半的时间。但是缺点就是相对来说消耗大量的内存。所以在考虑问题是,也要权衡时间复杂度和空间复杂度,针对实际情况进行选择。
c.这道题还有个解法是先将数组进行排序,如果出现相邻两个相等,则return true.排序只需要以下一个命令。
sort(nums.begin(), nums.end());
相关文章推荐
- MyBaits
- 十四步实现拥有强大AI的五子棋游戏
- 设计模式之责任链模式(ChainOfResponsibility)&正反顺逆链处理
- 06.RAID
- Flash Download Failed-"Cortex-M3"
- Flash Download Failed-"Cortex-M3"
- lightoj 1236 - Pairs Forming LCM 【唯一分解定理】
- MapReduce任务分析与讨论MapReduce job explained
- tail 实现 +注释
- HDU1039 Easier Done Than Said?
- RAID简介与软RAID实现
- Codeforces 300D Painting Square (FFT)
- Codeforces 472G Design Tutorial: Increase the Constraints(分块+FFT)
- HDU.1023 Train Problem II【大数除法、卡特兰数】--用于求出栈的n种方式(3.15)
- 属性readwrite,readonly,assign,retain,copy,nonatomic 各是什么作用,在那种情况下用
- Error:Execution failed for task ':processDebugResources'.
- HDFS API文件上传报错 Exception in thread "main" .......: Wrong FS: file:///
- SGI STL (7) :: why stl containers have their own iterators?
- sakai作业系统
- HDU 2473 Junk-Mail Filter(并查集删点)